- 准备 Menu 对象
public class Menu {
private Integer id;
private String label;
private Integer orderNum;
private Integer pid;
private List<Menu> children;
public Menu(Integer id, String label, Integer orderNum, Integer pid) {
this.id = id;
this.label = label;
this.orderNum = orderNum;
this.pid = pid;
}
public List<Menu> getChildren() {
return children;
}
public void setChildren(List<Menu> children) {
this.children = children;
}
public Integer getId() {
return id;
}
public String getLabel() {
return label;
}
public Integer getOrderNum() {
return orderNum;
}
public Integer getPid() {
return pid;
}
@Override
public String toString() {
return "Menu{" +
"id=" + id +
", label='" + label + '\'' +
", orderNum=" + orderNum +
", pid=" + pid +
", children=" + children +
'}';
}
}
- 构建MenuList 数据
public class MenuList {
public static final List<Menu> MENU_LIST=new ArrayList<>();
static {
MENU_LIST.add(new Menu(1,"1菜单",1,0));
MENU_LIST.add(new Menu(6,"1-2菜单",2,1));
MENU_LIST.add(new Menu(7,"1-2-1菜单",1,6));
MENU_LIST.add(new Menu(8,"1-3菜单",3,1));
MENU_LIST.add(new Menu(5,"1-1菜单",1,1));
MENU_LIST.add(new Menu(2,"2菜单",2,0));
MENU_LIST.add(new Menu(7,"2-1菜单",1,2));
MENU_LIST.add(new Menu(9,"2-2菜单-4",2,2));
MENU_LIST.add(new Menu(3,"3菜单",3,0));
MENU_LIST.add(new Menu(4,"4菜单",4,0));
}
}
- 通过 MenuList 构建目录树
public class DemoTest {
private static final List<Menu> MENU_LIST=MenuList.MENU_LIST;
public static void main(String[] args) throws JsonProcessingException {
List<Menu> rootMenus = MENU_LIST.stream().filter(item -> item.getPid().equals(0)).collect(Collectors.toList());
List<Menu> result = rootMenus.stream().map(item -> buildChildrenTree(item)).collect(Collectors.toList());
System.out.println(new ObjectMapper().writeValueAsString(result));
}
private static Menu buildChildrenTree(Menu rootMenu){
List<Menu> children = MENU_LIST.stream().filter(item -> item.getPid().equals(rootMenu.getId())).collect(Collectors.toList());
if (ObjectUtils.isEmpty(children)){
return rootMenu;
}
List<Menu> childrenResult=new ArrayList<>();
children.forEach(item->{
childrenResult.add(buildChildrenTree(item));
});
childrenResult.sort(Comparator.comparingInt(item -> item.getOrderNum()));
rootMenu.setChildren(childrenResult);
return rootMenu;
}
}
- 最终结果树
[{
"id": 1,
"label": "1菜单",
"orderNum": 1,
"pid": 0,
"children": [{
"id": 5,
"label": "1-1菜单",
"orderNum": 1,
"pid": 1,
"children": null
}, {
"id": 6,
"label": "1-2菜单",
"orderNum": 2,
"pid": 1,
"children": [{
"id": 7,
"label": "1-2-1菜单",
"orderNum": 1,
"pid": 6,
"children": null
}]
}, {
"id": 8,
"label": "1-3菜单",
"orderNum": 3,
"pid": 1,
"children": null
}]
}, {
"id": 2,
"label": "2菜单",
"orderNum": 2,
"pid": 0,
"children": [{
"id": 7,
"label": "2-1菜单",
"orderNum": 1,
"pid": 2,
"children": null
}, {
"id": 9,
"label": "2-2菜单-4",
"orderNum": 2,
"pid": 2,
"children": null
}]
}, {
"id": 3,
"label": "3菜单",
"orderNum": 3,
"pid": 0,
"children": null
}, {
"id": 4,
"label": "4菜单",
"orderNum": 4,
"pid": 0,
"children": null
}]