package org.sxkj.system.util;
|
import org.sxkj.system.entity.DictBiz;
|
|
import java.util.ArrayList;
|
import java.util.HashMap;
|
import java.util.List;
|
import java.util.Map;
|
import java.util.stream.Collectors;
|
|
public class TreeBuilder {
|
|
/**
|
* 构建树形结构
|
* @param list 原始数据列表
|
* @return 树形结构列表
|
*/
|
public static List<DictBiz> buildTree(List<DictBiz> list) {
|
// 用于存储id和对应的节点
|
Map<Long, DictBiz> nodeMap = new HashMap<>();
|
// 最终返回的树形结构
|
List<DictBiz> tree = new ArrayList<>();
|
|
// 第一遍遍历:将所有节点存入map,并初始化children列表
|
for (DictBiz node : list) {
|
nodeMap.put(node.getId(), node);
|
if (node.getChildrenList() == null) {
|
node.setChildrenList(new ArrayList<>());
|
}
|
}
|
|
// 第二遍遍历:建立父子关系
|
for (DictBiz node : list) {
|
Long parentId = node.getParentId();
|
if (parentId != null && parentId != 0) { // 假设0表示顶级节点
|
DictBiz parent = nodeMap.get(parentId);
|
if (parent != null) {
|
parent.getChildrenList().add(node);
|
}
|
} else {
|
// 没有父节点或父节点为0,认为是顶级节点
|
tree.add(node);
|
}
|
}
|
|
return tree;
|
}
|
|
/**
|
* 使用Stream API实现的树形结构构建
|
* @param list 原始数据列表
|
* @return 树形结构列表
|
*/
|
public static List<DictBiz> buildTreeWithStream(List<DictBiz> list) {
|
Map<Long, DictBiz> nodeMap = list.stream()
|
.collect(Collectors.toMap(DictBiz::getId, node -> node));
|
|
List<DictBiz> tree = new ArrayList<>();
|
|
list.forEach(node -> {
|
Long parentId = node.getParentId();
|
if (parentId != null && parentId != 0) {
|
DictBiz parent = nodeMap.get(parentId);
|
if (parent != null) {
|
if (parent.getChildrenList() == null) {
|
parent.setChildrenList(new ArrayList<>());
|
}
|
parent.getChildrenList().add(node);
|
}
|
} else {
|
tree.add(node);
|
}
|
});
|
|
return tree;
|
}
|
|
|
|
}
|