赞
踩
1.如何构建一棵森林/树?
public class Node {
private String id;
private String parentId;
private String name;
private List<Node> children = new ArrayList<>();
public Node(String id, String parentId, String name) {
this.id = id;
this.parentId = parentId;
this.name = name;
}
......
}
public static List<Node> buildTree(Node parent,List<Node> nodes){
if(Objects.isNull(parent)){
return nodes.stream().filter(node->Objects.equals(node.getParentId(), 0)).map(node->{
node.getChildren().addAll(buildTree(node,nodes));
return node;
}).collect(Collectors.toList());
}else{
return nodes.stream().filter(node->Objects.equals(node.getParentId() , parent.getId())).map(node->{
node.getChildren().addAll(buildTree(node,nodes));
return node;
}).collect(Collectors.toList());
}
}
List<Node> nodes = new ArrayList<Node>(){
{
add(new Node(1,0,"动物-0"));
add(new Node(2,1,"无脊椎-1"));
add(new Node(3,2,"无外骨骼-1-1"));
add(new Node(4,3,"身体不分节-1-1-1"));
add(new Node(5,4,"涡虫-1-1-1-1"));
add(new Node(6,3,"身体分节-1-1-2"));
add(new Node(7,6,"蚯蚓-1-1-2-1"));
add(new Node(8,2,"有外骨骼-1-2"));
add(new Node(9,8,"有翅-1-2-1"));
add
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。