树形结构和普通list数据的互换
1. list转树形结构
public static List<RetTreePath> list2tree(List<RetTreePath> list) {
List<RetTreePath> result = new ArrayList<>();
Map<Long, RetTreePath> map = list.stream().collect(Collectors.toMap(test -> test.getId(), test -> test));
for (RetTreePath test : list) {
RetTreePath p = map.get(test.getParentId());
if (p == null) {
result.add(test);
} else {
if (p.getChildren() == null) {
p.setChildren(new ArrayList<>());
}
p.getChildren().add(test);
}
}
return result;
}
二. 树形结构转list
public static List<RetTreePath> tree2list(List<RetTreePath> list) {
List<RetTreePath> result = new ArrayList<>();
for (RetTreePath retTreePath : list) {
List<RetTreePath> c = retTreePath.getChildren();
result.add(retTreePath);
if (!CollectionUtils.isEmpty(c)) {
result.addAll(tree2list(c));
retTreePath.setChildren(null);
}
}
return result;
}