package org.sxkj.system.util;
|
|
import org.springframework.util.CollectionUtils;
|
import org.sxkj.system.entity.DictBiz;
|
|
import java.util.*;
|
|
public class LevelDataMerger {
|
|
|
/**
|
* 按层级分组的数据,key为层级(从0开始),value为该层所有节点
|
*
|
* @param list
|
* @return
|
*/
|
public static Map<Integer, List<DictBiz>> buildMap(List<DictBiz> list) {
|
if(CollectionUtils.isEmpty(list)) {
|
return Collections.emptyMap();
|
}
|
List<DictBiz> listzz = TreeBuilder.buildTree(list);
|
if (CollectionUtils.isEmpty(listzz)) {
|
return Collections.emptyMap();
|
}
|
return mergeByLevel(listzz);
|
}
|
|
/**
|
* 按层级合并树形结构数据
|
*
|
* @param tree 树形结构数据
|
* @return 按层级分组的数据,key为层级(从0开始),value为该层所有节点
|
*/
|
public static Map<Integer, List<DictBiz>> mergeByLevel(List<DictBiz> tree) {
|
Map<Integer, List<DictBiz>> levelMap = new LinkedHashMap<>();
|
traverseTree(tree, 0, levelMap);
|
return levelMap;
|
}
|
|
/**
|
* 递归遍历树形结构
|
*
|
* @param nodes 当前层节点
|
* @param level 当前层级
|
* @param levelMap 结果存储Map
|
*/
|
private static void traverseTree(List<DictBiz> nodes, int level, Map<Integer, List<DictBiz>> levelMap) {
|
if (nodes == null || nodes.isEmpty()) {
|
return;
|
}
|
|
// 获取或创建当前层级的List
|
List<DictBiz> currentLevelList = levelMap.computeIfAbsent(level, k -> new ArrayList<>());
|
|
// 将当前层所有节点添加到对应层级的List中
|
currentLevelList.addAll(nodes);
|
|
// 递归处理每个节点的子节点
|
for (DictBiz node : nodes) {
|
if (node.getChildrenList() != null && !node.getChildrenList().isEmpty()) {
|
traverseTree(node.getChildrenList(), level + 1, levelMap);
|
}
|
}
|
}
|
|
/**
|
* 非递归方式实现层级合并(广度优先遍历)
|
*
|
* @param tree 树形结构数据
|
* @return 按层级分组的数据
|
*/
|
public static Map<Integer, List<DictBiz>> mergeByLevelBFS(List<DictBiz> tree) {
|
Map<Integer, List<DictBiz>> levelMap = new LinkedHashMap<>();
|
if (tree == null || tree.isEmpty()) {
|
return levelMap;
|
}
|
|
List<DictBiz> currentLevel = new ArrayList<>(tree);
|
int level = 0;
|
|
while (!currentLevel.isEmpty()) {
|
// 添加当前层级节点
|
levelMap.put(level, new ArrayList<>(currentLevel));
|
|
// 准备下一层级节点
|
List<DictBiz> nextLevel = new ArrayList<>();
|
for (DictBiz node : currentLevel) {
|
if (node.getChildrenList() != null) {
|
nextLevel.addAll(node.getChildrenList());
|
}
|
}
|
|
currentLevel = nextLevel;
|
level++;
|
}
|
|
return levelMap;
|
}
|
}
|