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 > List buildTree(List list) { List treeNodes = new ArrayList<>(); List rootNodes = getRootNodes(list); list.removeAll(rootNodes); for (T rootNode : rootNodes) { buildChildNodes(rootNode, list); treeNodes.add(rootNode); } return treeNodes; } /** * 递归子节点 * * @param node 根节点 * @param list 未构建的数据 */ public static void buildChildNodes(T node, List list) { List 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父节点下子集 */ public static List getChildNodes(T parent, List list) { List children = list.stream().filter(x -> parent.getId().equals(x.getParentId())).collect(Collectors.toList()); return children; } /** * 获取集合中所有的根节点 * * @param list 为构建的数据 * @return List 所有有子集的节点 */ public static List getRootNodes(List list) { List rootNodes = new ArrayList<>(); for (T n : list) { if (rootNode(n, list)) { rootNodes.add(n); } } return rootNodes; } /** * 判断是否为根节点 * * @param node 父级节点 * @param list 未构建的数据 * @return boolean是否有子集 */ public static boolean rootNode(T node, List list) { //判断是否有父级 List parents = list.stream().filter(x -> node.getParentId().equals(x.getId())).collect(Collectors.toList()); return CollectionUtil.isEmpty(parents); } }