使用递归构建树结构数据
前段时间公司项目需求需要生成树状结构的数据,在这里记录一下!
entity类
在同一张表里存在parentId和id(子id),当parentId为null时表示这就是树结构的最高层
@Data
public class DanalyIndexAlgotithm{
//主键id
private String id
//姓名
private String name
//优先级(这个项目中用到了这个字段,看情况而定,可以去掉)
private String priority
//父id
private String parentId
//子集数据
private List<DanalyIndexAlgotithm> children;
}
递归
public static List<DanalyIndexAlgorithm> buildTree(List<DanalyIndexAlgotithm> nodes){
List<DanalyIndexAlgorithm> tree = new ArrayList();
for(DanalyIndexAlgorithm node : nodes){
if(node.getParentId() == null){//根节点
//根节点的顺序为0
tree.add(node);
node.setNum(1);
build(node,nodes,"1");//递归
}
}
return tree;
}
//递归,构建树结构
public static void build(DanalyIndexAlgorithm node, List<DanalyIndexAlgorithm>nodes, String count){
if(!children.isEmpty){
node.setChildren(children);
for(DanalyIndexAlgorithm child : children){
build(child,nodes,count);
}
}
}
//构建子集数据
public static List<DanalyIndexAlgorithm> getChildren(DanalyIndexAlgorithm node,List<DanalyIndexAlgorithm> nodes,String count){
List<DanalyIndexAlgorithm> children = new ArrayList();
for(DanalyIndexAlgorithm org : nodes){
String pId = org.getParentId();
if(node.getId().equals(pId)){
org.setNum(Integer.valueOf(count) + 1 + "");
children.add(org);
}
}
return children;
}