对象需要有id,pid
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());
}