Java快速构建树结构数据(不需要递归)

头像
码农笔录
2023-02-22 后端 阅读量 2214

构建树形结构

@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()); //将这些非顶级节点的数据按pid进行分组 Map<Long, List<TreeNode>> sub = list.stream().collect(Collectors.groupingBy(node -> node.getPid())); //循环设置对应的子节点(根据id = pid) nodes.forEach(node -> node.setChildren(sub.get(node.getId()))); //只留下顶级节点,自动成树形结构 List<TreeNode> collect = nodes.stream().filter(node -> node.getPid() == null).collect(Collectors.toList()); return collect; } }