史上最简单的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

浙公网安备 33010602011771号