Java递归处理Tree树结构

Java递归处理Tree树结构

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
package cn.pconline;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @Description Tree树结构数据组装
* @Author jie.zhao
* @Date 2019/12/27 15:10
*/
public class TestTree {

public static void main(String[] args) {
//假数据
List<Map<String, Object>> dataList = new ArrayList<>();
dataList.add(new HashMap<String, Object>() {{
put("id", "1");
put("pid", "");
put("name", "公司根节点");
}});
dataList.add(new HashMap<String, Object>() {{
put("id", "2");
put("pid", "1");
put("name", "部门1");
}});
dataList.add(new HashMap<String, Object>() {{
put("id", "3");
put("pid", "1");
put("name", "部门2");
}});
dataList.add(new HashMap<String, Object>() {{
put("id", "4");
put("pid", "2");
put("name", "部门1小组1");
}});
dataList.add(new HashMap<String, Object>() {{
put("id", "5");
put("pid", "3");
put("name", "部门2小组1");
}});

//dataList为假数据,正常数据库查询所有数据。。。
List<Map<String, Object>> treeList = doTreeList(dataList, "");
System.out.println(JSON.toJSONString(treeList));
//输出
/*
[{"children":[{"children":[{"children":[],"name":"部门1小组1","pid":"2","id":"4"}],"name":"部门1","pid":"1","id":"2"},
{"children":[{"children":[],"name":"部门2小组1","pid":"3","id":"5"}],
"name":"部门2","pid":"1","id":"3"}],"name":"公司根节点","pid":"","id":"1"}]
*/

}

//递归tree树
public static List<Map<String, Object>> doTreeList(List<Map<String, Object>> dataList, String pid) {
List<Map<String, Object>> resultList = new ArrayList<>();
if (dataList != null) {
for (Map<String, Object> item : dataList) {
if (pid.equals(item.get("pid").toString())) {
List<Map<String, Object>> children = doTreeList(dataList, item.get("id").toString());
item.put("children", children);
resultList.add(item);
}
}
}
return resultList;
}
}
-------------已经触及底线 感谢您的阅读-------------

本文标题:Java递归处理Tree树结构

文章作者:趙小傑~~

发布时间:2019年12月27日 - 14:59:36

最后更新:2020年03月01日 - 19:50:39

原始链接:https://cnsyear.com/posts/1a591889.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%