记一个递归封装树形结构

记一个递归封装树形结构

viEcho Lv5

最近改了个小bug,原有的数据字典查询,封装成树的递归写的有问题,就自己写了一个,解决这种递归的思考是:分析树形结构–>>找到父子层之间的关联关系–>>根据关系编写递归嵌套条件。代码很简单也很实用,遂总结如下

表结构

截取表结构如下,关联id 和pid(父id).其中树最外层pid为0

代码逻辑

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
public List<Map<String, Object>> getRootDict() {
List<Map<String, Object>> returnList = new ArrayList<>();
// 查询所有数据字典
List<Map<String, Object>> dictList = dictMapper.getAllDict();
Map<String, Object> map = new HashMap<>(16);
map.put("name", "数据字典");
map.put("id", null);
map.put("pid", null);

// 构建树形结构
List<Map<String, Object>> rootTree = this.rebuildRootTree("0",dictList);
map.put("child", rootTree);
returnList.add(map);
return returnList;
}

/**
* 构建树结构
* @param pid
* @param dictList
* @return
*/
List<Map<String, Object>> rebuildRootTree(String pid ,List<Map<String, Object>> dictList){
List<Map<String, Object>> rootTree = new ArrayList<>();
for(Map<String, Object> dictMap:dictList){
if(dictMap.containsKey("pid") && Objects.equals(dictMap.get("pid").toString(),pid)) {
Map<String, Object> newMap = new HashMap<>(16);
newMap.put("name", dictMap.get("name"));
newMap.put("id", dictMap.get("id"));
newMap.put("pid", dictMap.get("pid"));
//递归调用
newMap.put("child",this.rebuildRootTree((dictMap.get("id")).toString(),dictList));
rootTree.add(newMap);
}
}
return rootTree;
}

若为实体,替换为对应的实体类即可;好了,就酱!日常生活的小技巧,还是总结下

  • Title: 记一个递归封装树形结构
  • Author: viEcho
  • Created at : 2021-04-23 19:55:09
  • Updated at : 2024-01-18 14:51:34
  • Link: https://viecho.github.io/2021/0423/recursion-for-tree.html
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
记一个递归封装树形结构