史上最简单的JAVA集合(List)转树(Tree)方法

    /**
     * 将数据转换为树型结构
     *
     * @param sources sources
     * @return {@link List<DemoData>}
     */
    public static List<DemoData> transToTree(List<DemoData> sources) {
        if (CollectionUtils.isEmpty(sources)) {
            return Collections.emptyList();
        }
        Map<Integer, DemoData> sourceMap = sources.stream().collect(Collectors.toMap(DemoData::getId, e -> e));
        Map<Integer, List<DemoData>> pIdToChildrenListMap = sources.stream().collect(Collectors.groupingBy(DemoData::getPid));
        List<Integer> willBeRemovedIdList = new LinkedList<>();
        for (Map.Entry<Integer, List<DemoData>> entry : pIdToChildrenListMap.entrySet()) {
            DemoData demoData = sourceMap.get(entry.getKey());
            if (demoData == null) {
                continue;
            }
            demoData.setChildren(entry.getValue().stream().sorted(Comparator.comparing(DemoData::getSort)).collect(Collectors.toList()));
            willBeRemovedIdList.add(entry.getKey());
        }
        willBeRemovedIdList.forEach(pIdToChildrenListMap::remove);
        // 获取顶级
        return pIdToChildrenListMap.values().stream().flatMap(Collection::stream).sorted(Comparator.comparing(DemoData::getSort)).collect(Collectors.toList());
    }

摘抄自:https://blog.csdn.net/u013902368/article/details/113534197

posted @ 2022-07-14 16:38  yanglei.xyz  阅读(1625)  评论(0)    收藏  举报