根据id、parentId、depth(层级)组装树
需要处理的list
[{
"ID": "1",
"ParentID": "0",
"DepartmentName": "一级菜单",
"Depth": 0
}, {
"ID": "2",
"ParentID": "1",
"DepartmentName": "二级菜单",
"Depth": 1
}, {
"ID": "3",
"ParentID": "2",
"DepartmentName": "三级菜单",
"Depth": 2
}, {
"ID": "4",
"ParentID": "3",
"DepartmentName": "四级菜单",
"Depth": 3
}]
实体类
@Data
public class TestVo {
@ApiModelProperty("ID")
private String ID;
@ApiModelProperty("父ID")
private String ParentID;
@ApiModelProperty("菜单名称")
private String DepartmentName;
@ApiModelProperty("层级")
private String Depth;
@ApiModelProperty("排序")
private Integer sort;
List<TestVo> children;
}
实现方法
public static void main(String[] args) {
String data = "[{\"ID\":\"1\",\"ParentID\":\"0\",\"DepartmentName\":\"一级菜单\",\"Depth\":0},{\"ID\":\"2\",\"ParentID\":\"1\",\"DepartmentName\":\"二级菜单\",\"Depth\":1},{\"ID\":\"3\",\"ParentID\":\"2\",\"DepartmentName\":\"三级菜单\",\"Depth\":2},{\"ID\":\"4\",\"ParentID\":\"3\",\"DepartmentName\":\"四级菜单\",\"Depth\":3}]";
List<TestVo> dataList = JSONObject.parseArray(data, TestVo.class);
System.out.println( JSONArray.toJSONString(listWithTree(dataList)));
}
public static List<TestVo> listWithTree(List<TestVo> dataList) {
//1、组装成父子的树形结构
List<TestVo> list = dataList.stream().filter(categoryEntity ->
categoryEntity.getParentID().equals("0"))
.map(menu -> {
menu.setChildren(getChildren(menu, dataList));
return menu;
})
.sorted((m1, m2) -> {
return (m1.getSort() == null ? 0 : m1.getSort()) - (m2.getSort() == null ? 0 : m2.getSort());
}).collect(Collectors.toList());
return list;
}
public static List<TestVo> getChildren(TestVo menu, List<TestVo> all) {
List<TestVo> childrenList = all.stream().filter(categoryEntity -> categoryEntity.getParentID().equals(menu.getID()))
.map(m -> {
//1. 找到子菜单
m.setChildren(getChildren(m, all));
return m;
}).sorted((m1, m2) -> {
//2、菜单的排序
return (m1.getSort() == null ? 0 : m1.getSort()) - (m2.getSort() == null ? 0 : m2.getSort());
}).collect(Collectors.toList());
return childrenList;
}
运行结果
[{
"children": [{
"children": [{
"children": [{
"children": [],
"departmentName": "四级菜单",
"depth": "3",
"iD": "4",
"parentID": "3"
}],
"departmentName": "三级菜单",
"depth": "2",
"iD": "3",
"parentID": "2"
}],
"departmentName": "二级菜单",
"depth": "1",
"iD": "2",
"parentID": "1"
}],
"departmentName": "一级菜单",
"depth": "0",
"iD": "1",
"parentID": "0"
}]
参考链接:
https://www.cnblogs.com/homle/p/17011327.html