public List<Map<String, Object>> parseTree(List<Map<String, Object>> list) {
List<Map<String, Object>> resultList = new ArrayList<>();
//zMap存储的均为id为key的键值对
Map<String, Map<String, Object>> zMap = new HashMap<>();
for (int i = 0, l = list.size(); i < l; i++) {
zMap.put(String.valueOf(list.get(i).get("id")), list.get(i));
}
for (int i = 0, l = list.size(); i < l; i++) {
Map<String, Object> map = list.get(i);
//如果以pid为key可以取出对象,则表明该元素是父级元素
if(zMap.get(map.get("pid")) != null){
Map<String, Object> pMap = zMap.get(map.get("pid"));
//给当前这个父级map对象中添加key为children的ArrayList
if (pMap.get("children") == null) {
pMap.put("children", new ArrayList<Map<String, Object>>());
}
List<Map<String, Object>> cList = (ArrayList<Map<String, Object>>) pMap.get("children");
cList.add(list.get(i));
} else {
resultList.add(list.get(i));
}
}
return resultList;
}
java树结构(map)
于 2022-02-22 16:39:14 首次发布