package cn.besteam.common.util.tree;
|
|
import cn.hutool.core.collection.CollectionUtil;
|
|
import java.util.ArrayList;
|
import java.util.List;
|
import java.util.stream.Collectors;
|
|
/**
|
* 树形结构工具类
|
*
|
* @author A
|
*/
|
|
public class TreeUtils {
|
|
/**
|
* 构建树形结构入口方法
|
*
|
* @param list 待构建的数据
|
* @return 构建后的树形结构
|
*/
|
public static <T extends TreeNode<T>> List<T> buildTree(List<T> list) {
|
List<T> treeNodes = new ArrayList<>();
|
List<T> rootNodes = getRootNodes(list);
|
list.removeAll(rootNodes);
|
for (T rootNode : rootNodes) {
|
buildChildNodes(rootNode, list);
|
treeNodes.add(rootNode);
|
}
|
return treeNodes;
|
}
|
|
/**
|
* 递归子节点
|
*
|
* @param node 根节点
|
* @param list 未构建的数据
|
*/
|
public static <T extends TreeNode> void buildChildNodes(T node, List<T> list) {
|
List<T> children = getChildNodes(node, list);
|
list.removeAll(children);
|
if (!children.isEmpty()) {
|
for (T child : children) {
|
buildChildNodes(child, list);
|
}
|
node.setChildren(children);
|
}
|
}
|
|
/**
|
* 获取父节点下所有的子节点
|
*
|
* @param parent 父节点
|
* @param list 未构建的数据
|
* @return List<TreeNode>父节点下子集
|
*/
|
public static <T extends TreeNode> List<T> getChildNodes(T parent, List<T> list) {
|
List<T> children = list.stream().filter(x -> parent.getId().equals(x.getParentId())).collect(Collectors.toList());
|
return children;
|
}
|
|
|
/**
|
* 获取集合中所有的根节点
|
*
|
* @param list 为构建的数据
|
* @return List<TreeNode> 所有有子集的节点
|
*/
|
public static <T extends TreeNode> List<T> getRootNodes(List<T> list) {
|
List<T> rootNodes = new ArrayList<>();
|
for (T n : list) {
|
if (rootNode(n, list)) {
|
rootNodes.add(n);
|
}
|
}
|
return rootNodes;
|
}
|
|
/**
|
* 判断是否为根节点
|
*
|
* @param node 父级节点
|
* @param list 未构建的数据
|
* @return boolean是否有子集
|
*/
|
public static <T extends TreeNode> boolean rootNode(T node, List<T> list) {
|
//判断是否有父级
|
List<T> parents = list.stream().filter(x -> node.getParentId().equals(x.getId())).collect(Collectors.toList());
|
return CollectionUtil.isEmpty(parents);
|
}
|
}
|