构建树形结构
@Data
public class TreeNode {
private Long id;
private Long pid;
private String name;
private List<TreeNode> children = new ArrayList<>();
public TreeNode(Long id, Long pid) {
this.id = id;
this.pid = pid;
}
public TreeNode(Long id, Long pid, String name) {
this(id, pid);
this.name = name;
}
}
遍历数据构建树
public class TreeUtil {
public static List<TreeNode> buildTree(List<TreeNode> nodes) {
List<TreeNode> list = nodes.stream().filter(node -> node.getPid() != null).collect(Collectors.toList());
Map<Long, List<TreeNode>> sub = list.stream().collect(Collectors.groupingBy(node -> node.getPid()));
nodes.forEach(node -> node.setChildren(sub.get(node.getId())));
List<TreeNode> collect = nodes.stream().filter(node -> node.getPid() == null).collect(Collectors.toList());
return collect;
}
}