TreeUtil.java
1.32 KB
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
package com.bs.common.utils;
import com.bs.common.core.domain.Tree;
import java.util.ArrayList;
import java.util.List;
/**
* 树工具类
*/
public class TreeUtil {
private final static Long TOP_NODE_ID = 0l;
/**
* 御用构建树
*
* @param nodes nodes
* @return <T> List<? extends Tree>
*/
public static <T> List<? extends Tree<?>> build(List<? extends Tree<T>> nodes) {
if (nodes == null) {
return null;
}
List<Tree<T>> topNodes = new ArrayList<>();
nodes.forEach(node -> {
Long pid = node.getParentId();
if (pid == null || TOP_NODE_ID.equals(pid)) {
topNodes.add(node);
return;
}
for (Tree<T> n : nodes) {
Long id = n.getId();
if (id != null && id.equals(pid)) {
if (n.getChildren() == null) {
n.initChildren();
}
n.getChildren().add(node);
node.setHasParent(true);
n.setHasChildren(true);
n.setHasParent(true);
return;
}
}
if (topNodes.isEmpty()) {
topNodes.add(node);
}
});
return topNodes;
}
}