0%

Java多级树工具类

记录一下Java解析多级树的工具类

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
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
* @author: perhamer
* @date: 2020-07-07 14:31
*/
public class TreeUtils {

public static <T extends TreeNode<T>> List<T> getTree(List<T> rootList, List<T> childList) {
List<T> treeNodeList = new ArrayList<>();
for (T node : rootList) {
Set<String> existsIds = new HashSet<>();
List<T> childrenTreeNodes = getChild(node.getNode(), childList, existsIds);
node.setChildren(childrenTreeNodes);
treeNodeList.add(node);
}
return treeNodeList;
}

private static <T extends TreeNode<T>> List<T> getChild(String parentId, List<T> childList, Set<String> existsIds) {
List<T> children = new ArrayList<>();
for (T node : childList) {
if (existsIds.contains(node.getNode())) {
continue;
}
if (node.getParent().equals(parentId)) {
node.setChildren(getChild(node.getNode(), childList, existsIds));
existsIds.add(node.getNode());
children.add(node);
}
}
return children;
}
@Data
public static class TreeNode<T> {

@JsonIgnore
String node;

@JsonIgnore
String parent;

List<T> children;
}
}