直接撸代码吧
@Override
public CommonResult treList() {
List<HashMap<String,Object>> returnList = new ArrayList<>();
List<HashMap<String,Object>> alllist = this.baseMapper.treeList();
for (HashMap<String,Object> hashMap : alllist){
if ("0".equals(hashMap.get("parentId").toString())) {
returnList.add(findChildren(hashMap, alllist));
}
}
return CommonResult.ok().value(returnList);
}
private HashMap<String,Object> findChildren(HashMap<String,Object> cHashMap, List<HashMap<String,Object>> allList) {
List<HashMap<String,Object>> childrenList = new ArrayList<>();
for (HashMap<String,Object> hashMap : allList) {
if (hashMap.get("parentId").toString().equals(cHashMap.get("id").toString())) {
childrenList.add(findChildren(hashMap, allList));
}
}
cHashMap.put("children",childrenList);
return cHashMap;
}
数据库设计 表字段需要有 主键ID(id)和 父级ID(parentId) ,一级的父级ID 默认0
我觉得我的写法有点麻烦,最好能两行搞定懒得去想,大佬路过请留点评
|