diff --git a/CHANGELOG.md b/CHANGELOG.md index a8e214241..7b799da02 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,9 +2,11 @@ # 🚀Changelog ------------------------------------------------------------------------------------------------------------- -# 5.8.31(2024-08-09) +# 5.8.31(2024-08-11) ### 🐣新特性 +* 【core 】 TreeUtil增加build方法,可以构建Bean的树结构(pr#3692@Github) + ### 🐞Bug修复 * 【extra 】 修复JakartaMailUtil引用javax的问题 diff --git a/hutool-core/src/main/java/cn/hutool/core/lang/tree/TreeUtil.java b/hutool-core/src/main/java/cn/hutool/core/lang/tree/TreeUtil.java index e44bc3c9e..69ad8233a 100755 --- a/hutool-core/src/main/java/cn/hutool/core/lang/tree/TreeUtil.java +++ b/hutool-core/src/main/java/cn/hutool/core/lang/tree/TreeUtil.java @@ -291,9 +291,12 @@ public class TreeUtil { * @param 节点类型 * @return List */ - public static List build(List nodes, T rootId, Function idFunc, Function parentIdFunc, BiConsumer> setChildFunc) { + public static List build(List nodes, T rootId, + Function idFunc, + Function parentIdFunc, + BiConsumer> setChildFunc) { List rootList = nodes.stream().filter(tree -> parentIdFunc.apply(tree).equals(rootId)).collect(Collectors.toList()); - Map filterOperated = new HashMap<>(rootList.size() + nodes.size()); + Set filterOperated = new HashSet<>(rootList.size() + nodes.size()); //对每个根节点都封装它的孩子节点 rootList.forEach(root -> setChildren(root, nodes, filterOperated, idFunc, parentIdFunc, setChildFunc)); return rootList; @@ -311,15 +314,15 @@ public class TreeUtil { * @param 节点ID类型 * @param 节点类型 */ - private static void setChildren(E root, List nodes, Map filterOperated, Function idFunc, Function parentIdFunc, BiConsumer> setChildFunc) { + private static void setChildren(E root, List nodes, Set filterOperated, Function idFunc, Function parentIdFunc, BiConsumer> setChildFunc) { List children = new ArrayList<>(); nodes.stream() //过滤出未操作过的节点 - .filter(body -> !filterOperated.containsKey(idFunc.apply(body))) + .filter(body -> !filterOperated.contains(idFunc.apply(body))) //过滤出孩子节点 .filter(body -> Objects.equals(idFunc.apply(root), parentIdFunc.apply(body))) .forEach(body -> { - filterOperated.put(idFunc.apply(body), idFunc.apply(root)); + filterOperated.add(idFunc.apply(body)); children.add(body); //递归 对每个孩子节点执行同样操作 setChildren(body, nodes, filterOperated, idFunc, parentIdFunc, setChildFunc);