package com.cyc.basic.test.list;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class ParentChildListTest {
public static void main(String[] args) {
List<Menu> menus = Arrays.asList(
new Menu(1, "根节点", 0),
new Menu(2, "父节点1", 1),
new Menu(3, "子节点1.1", 2),
new Menu(4, "子节点1.2", 2),
new Menu(5, "子节点1.3", 2),
new Menu(6, "父节点2", 1),
new Menu(7, "子节点2.1", 6),
new Menu(8, "子节点2.2", 6),
new Menu(9, "子子节点2.2.1", 7),
new Menu(10, "子子节点2.2.2", 7),
new Menu(11, "父节点3", 1),
new Menu(12, "子节点3.1", 11)
);
List<Menu> collect = menus.stream().filter(m -> m.getParentId() == 0).map(
menu -> {
menu.setChildList(getChildrens(menu, menus));
return menu;
}
).collect(Collectors.toList());
List<Menu> collect2 = menus.stream().filter(menu -> menu.getParentId() == 0).peek(
menu -> menu.setChildList(getChildrens(menu, menus))
).collect(Collectors.toList());
System.out.println("-------转json输出结果-------");
System.out.println(JSON.toJSON(collect));
}
private static List<Menu> getChildrens(Menu root, List<Menu> all) {
List<Menu> children = all.stream().filter(menu -> Objects.equals(menu.getParentId(), root.getId()))
.map(menu -> {
menu.setChildList(getChildrens(menu, all));
return menu;
}
).collect(Collectors.toList());
return children;
}
}
@Data
class Menu {
public Integer id;
public String name;
public Integer parentId;
public List<Menu> childList;
public Menu(Integer id, String name, Integer parentId) {
this.id = id;
this.name = name;
this.parentId = parentId;
}
}
输出结果
[{
"name": "根节点",
"childList": [{
"name": "父节点1",
"childList": [{
"name": "子节点1.1",
"childList": [],
"id": 3,
"parentId": 2
}, {
"name": "子节点1.2",
"childList": [],
"id": 4,
"parentId": 2
}, {
"name": "子节点1.3",
"childList": [],
"id": 5,
"parentId": 2
}],
"id": 2,
"parentId": 1
}, {
"name": "父节点2",
"childList": [{
"name": "子节点2.1",
"childList": [{
"name": "子子节点2.2.1",
"childList": [],
"id": 9,
"parentId": 7
}, {
"name": "子子节点2.2.2",
"childList": [],
"id": 10,
"parentId": 7
}],
"id": 7,
"parentId": 6
}, {
"name": "子节点2.2",
"childList": [],
"id": 8,
"parentId": 6
}],
"id": 6,
"parentId": 1
}, {
"name": "父节点3",
"childList": [{
"name": "子节点3.1",
"childList": [],
"id": 12,
"parentId": 11
}],
"id": 11,
"parentId": 1
}],
"id": 1,
"parentId": 0
}]