以下是对代码的优化建议:

  1. 使用方法引用来简化代码。可以将BaseTreeEntity::getParentIdMapUtils.getObject替换为T::getParentIdMapUtils::getObject

  2. 使用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;
        }));
  1. 使用Stream#filterStream#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());
  1. 可以将Collections::singletonList替换为Arrays::asList,以便支持多个子节点。

通过以上优化,可以使代码更简洁和易读

代码优化: public static T extends BaseTreeEntityT ListT buildTreeListT nodes final MapString ListT childrenNodeGroup = CollectionUtilsemptyIfNullnodesstream filterl - !lisRoot

原文地址: http://www.cveoy.top/t/topic/iPYS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录