根据parentId构建树结构
该结构在企业开发中,通过遍历数据库中的数据构建树型结构很常用
Node结构:
@Data
public class Node {
private String cId; //id
private String cName; //name
private String parentId;
private List<Node> children;
public Node(String cId, String cName, String parentId, List<Node> children) {
this.cId = cId;
this.cName = cName;
this.children = children;
this.parentId = parentId;
}
一、测试数据:
public static List<Node> getData() {
Node node1 = new Node("1", "节点a", "0", null);
Node node2 = new Node("2", "节点b", "1", null);
Node node3 = new Node("3", "节点c", "1", null);
Node node4 = new Node("4", "节点d", "2", null);
List<Node> datas = new ArrayList<>(7);
datas.add(node1);
datas.add(node2);
datas.add(node3);
datas.add(node4);
return datas;
}
二、通过递归给每个Node的parentId为0的节点(根节点parentId为0)构建子节点
public Node buildChildern(Node node,List<Node> nodes){
List<Node> children = new ArrayList<>();
if(node != null){
nodes.forEach((o)->{
if(o.getParentId().equals(node.cId)){
children.add(buildChildern(o,nodes)); //递归调用
}
});
}
node.setChildren(children);
return node;
}
三、找出其中的根节点
public List<Node> getRootNode(List<Node> nodes){
List<Node> roots = new ArrayList<>();
nodes.forEach(o->{
if(o.getParentId().equals("0")){
roots.add(o);
}
});
return roots;
}
四、最后构建树
public List<Node> builTree(List<Node> nodes){
List<Node> roots = new ArrayList<>() ;
getRootNode(nodes).forEach(o->{
Node node = buildChildern(o, nodes);
roots.add(node);
});
return roots;
}