Java递归处理Tree树结构
Java递归处理Tree树结构
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;
}
}
-------------已经触及底线 感谢您的阅读-------------