ZQN
2024-06-17 b1ff19545212508d3f65741ab889f0b6df82a511
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
package com.project.common.core.absclasses;
 
 
import com.project.common.core.interfaces.ITreeNode;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
 
public class TreeNodeManager<T extends ITreeNode<T>>
{
 
    private final ImmutableMap<Long, T> nodeMap;
    private final Map<Long, Object> parentIdMap = Maps.newHashMap();
 
    public TreeNodeManager(List<T> nodes) {
        this.nodeMap = Maps.uniqueIndex(nodes, ITreeNode::getId);
    }
 
    public ITreeNode<T> getTreeNodeAt(Long id) {
        return this.nodeMap.containsKey(id) ? (ITreeNode) this.nodeMap.get(id) : null;
    }
 
    public void addParentId(Long parentId) {
        this.parentIdMap.put(parentId, "");
    }
 
    public List<T> getRoot() {
        List<T> roots = new ArrayList();
        this.nodeMap.forEach((key, node) -> {
            if (node.getParentId() == 0L || this.parentIdMap.containsKey(node.getId())) {
                roots.add(node);
            }
 
        });
        return roots;
    }
}