代码优化: public static T extends BaseTreeEntityT ListT buildTreeListT nodes final MapString ListT childrenNodeGroup = CollectionUtilsemptyIfNullnodesstream filterl - !lisRoot
以下是对代码的优化建议:
-
使用方法引用来简化代码。可以将
BaseTreeEntity::getParentId和MapUtils.getObject替换为T::getParentId和MapUtils::getObject。 -
使用
Stream#collect方法的Collectors.toMap来替换Collectors.groupingBy,以简化代码。可以通过以下方式来构建childrenNodeGroup:
final Map<String, List<T>> childrenNodeGroup = CollectionUtils.emptyIfNull(nodes)
.stream()
.filter(l -> !l.isRoot())
.collect(Collectors.toMap(T::getParentId, Collections::singletonList, (a, b) -> {
List<T> mergedList = new ArrayList<>(a);
mergedList.addAll(b);
return mergedList;
}));
- 使用
Stream#filter和Stream#map来替换两个CollectionUtils.emptyIfNull(nodes).stream()。可以通过以下方式来重构代码:
return nodes
.stream()
.filter(Objects::nonNull)
.filter(l -> !l.isRoot())
.collect(Collectors.toMap(T::getParentId, Collections::singletonList, (a, b) -> {
List<T> mergedList = new ArrayList<>(a);
mergedList.addAll(b);
return mergedList;
}))
.entrySet()
.stream()
.peek(entry -> entry.getKey().setChildrens(entry.getValue()))
.filter(entry -> entry.getKey().isRoot())
.map(Map.Entry::getKey)
.collect(Collectors.toList());
- 可以将
Collections::singletonList替换为Arrays::asList,以便支持多个子节点。
通过以上优化,可以使代码更简洁和易读
原文地址: http://www.cveoy.top/t/topic/iPYS 著作权归作者所有。请勿转载和采集!