缘由:能不递归就不递归
代码实现Demo
import com.alibaba.fastjson.JSON;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ListToTreeDemo {
private static class Node {
private int id;
private int pid;
private String name;
private List<Node> child;
public Node(int id, int pid) {
this.id = id;
this.pid = pid;
this.name = "测试:"+ pid + ":" + id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Node> getChild() {
return child;
}
public void setChild(List<Node> child) {
this.child = child;
}
}
public static void main(String[] args) {
List<Node> nodes = new ArrayList<>();
nodes.add(new Node(1, 0));
nodes.add(new Node(2, 0));
nodes.add(new Node(3, 0));
nodes.add(new Node(4, 0));
nodes.add(new Node(5, 1));
nodes.add(new Node(6, 1));
nodes.add(new Node(7, 2));
nodes.add(new Node(8, 5));
Map<Integer, List<Node>> collect = nodes.stream().collect(Collectors.groupingBy(Node::getPid));
nodes.forEach((item) -> {
if (CollectionUtils.isEmpty(collect.get(item.getId()))) {
item.setChild(new ArrayList<>());
} else {
item.setChild(collect.get(item.getId()));
}
});
List<Node> list = nodes
.stream()
.filter((item) -> item.getPid() == 0)
.collect(Collectors.toList());
System.out.println(JSON.toJSONString(list));
}
}