public static List<MenuInfo> buildTree(List<MenuInfo> nodes) {
Map<Integer, MenuInfo> nodeMap = nodes.stream()
.collect(Collectors.toMap(MenuInfo::getId, node -> node));
List<MenuInfo> roots = nodes.stream()
.filter(node -> !nodeMap.containsKey(node.getParentId()))
.collect(Collectors.toList());
attachChildren(roots, nodeMap);
return roots;
}
private static void attachChildren(List<MenuInfo> parents, Map<Integer, MenuInfo> nodeMap) {
for (MenuInfo parent : parents) {
List<MenuInfo> children = nodeMap.values().stream()
.filter(node -> Objects.equals(node.getParentId(), parent.getId()))
.collect(Collectors.toList());
parent.setChildren(children);
attachChildren(children, nodeMap);
}
}
06-01
352
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-06
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交