吉安感知网项目-后端
xiebin
2026-01-06 d207a86cdf1ab52ef8cb7cd83bad8fceab8038cf
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
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;
    }
 
 
 
}