医院废弃物信息化管理平台
“mitao”
2025-12-24 3763145f34d7706923d55edc32f5cfbc8bc08b92
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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);
    }
}