JAVA 封装多级树结构对象(通用)

前言

总结一下最近写的一段代码,可以实现各种树形结构封装。

Code

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
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.List;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
public class TreeUtil {
private List<TreeDto> rootList; //根节点
private List<TreeDto> bodyList; //子节点
public TreeUtil(List<TreeDto> rootList, List<TreeDto> bodyList) {
this.rootList = rootList;
this.bodyList = bodyList;
}
public List<TreeDto> getTree() {
if (CollectionUtils.isNotEmpty(bodyList)) {
Map<Long, Long> map = Maps.newHashMapWithExpectedSize(bodyList.size());
rootList.forEach(beanTree -> getChild(beanTree, map));
return rootList;
}
return null;
}
public void getChild(TreeDto beanTree, Map<Long, Long> map) {
List<TreeDto> childList = Lists.newArrayList();
bodyList.stream()
.filter(c -> !map.containsKey(c.getId()))
.filter(c -> c.getParentid().equals(beanTree.getId()))
.forEach(c -> {
map.put(c.getId(), c.getParentid());
getChild(c, map);
childList.add(c);
});
if (childList.size() > 0) {
beanTree.setChildren(childList);
}
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class TreeDto {
private Long id;
private String name;
private Long parentid;
private Boolean isChild;
private List<TreeDto> children;
}
}
----本文结束 感谢您的阅读----