这种制作树结构的过程建议一次性拿到全部数据,减少多次创建数据库链接数,在内存中执行,提高运行效率。写代码老忘,在此记录下。
public List<DeptVo> listToTree(List<DeptVo> list) {
List<DeptVo> treeList = new ArrayList<>();
List<DeptVo> rootList = list.stream().filter(vo -> vo.getParentId() == 0).collect(Collectors.toList());
rootList.forEach(tree -> treeList.add(findChildren(tree, list)));
return treeList;
}
private DeptVo findChildren(DeptVo tree, List<DeptVo> list) {
list.stream().filter(node -> tree.getId().equals(node.getParentId())).collect(Collectors.toList()).forEach(node -> {
if (tree.getChildren() == null) {
tree.setChildren(new ArrayList<>());
}
tree.getChildren().add(findChildren(node, list));
});
return tree;
}