扁平数据根据parentID构建树形结构
package com.example.duohoob.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
public class TreeList {
public static void main(String[] args) {
List<Map<String, Object>> maps = new ArrayList<Map<String,Object>>();
Map<String, Object> m1 = new HashMap<String, Object>();
m1.put("id", 1);
m1.put("name", "a");
m1.put("parentId", null);
maps.add(m1);
Map<String, Object> m2 = new HashMap<String, Object>();
m2.put("id", 2);
m2.put("name", "b");
m2.put("parentId", 1);
maps.add(m2);
Map<String, Object> m3 = new HashMap<String, Object>();
m3.put("id", 3);
m3.put("name", "c");
m3.put("parentId", null);
maps.add(m3);
Map<String, Object> m4 = new HashMap<String, Object>();
m4.put("id", 4);
m4.put("name", "d");
m4.put("parentId", 3);
maps.add(m4);
Map<String, Object> m5 = new HashMap<String, Object>();
m5.put("id", 5);
m5.put("name", "e");
m5.put("parentId", 4);
maps.add(m5);
System.out.println(JSON.toJSONString(maps));
List<Integer> idList = new ArrayList<Integer>(maps.size());
List<Map<String, Object>> roots = new ArrayList<Map<String,Object>>();
Map<Integer, List<Map<String, Object>>> children = new HashMap<Integer, List<Map<String,Object>>>();
for (Map<String, Object> map : maps) {
idList.add((Integer) map.get("id"));
}
for (Map<String, Object> map : maps) {
Integer parentId = (Integer) map.get("parentId");
if (idList.contains(parentId)) {
children.computeIfAbsent(parentId, key -> new ArrayList<Map<String, Object>>()).add(map);
} else {
roots.add(map);
}
}
setChildList(roots, children);
System.out.println(JSON.toJSONString(roots));
}
private static void setChildList(List<Map<String, Object>> roots, Map<Integer, List<Map<String, Object>>> children) {
for (Map<String, Object> parent : roots) {
List<Map<String, Object>> childList = children.get((Integer) parent.get("id"));
if (null != childList && childList.size() > 0) {
parent.put("childList", childList);
setChildList(childList, children);
}
}
}
}
[
{
"name":"a",
"childList":[
{
"name":"b",
"id":2,
"parentId":1
}
],
"id":1
},
{
"name":"c",
"childList":[
{
"name":"d",
"childList":[
{
"name":"e",
"id":5,
"parentId":4
}
],
"id":4,
"parentId":3
}
],
"id":3
}
]