定义一个实体
package com.tdy.tiger.trr;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class Menu {
private Integer id;//id
private Integer pid;//父id
private String name;//名称
List<Menu> child = new ArrayList<>();//子类
public Menu(Integer id,Integer pid, String name) {
this.id = id;
this.name = name;
this.pid = pid;
}
}
实现方法
package com.tdy.tiger.trr;
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
public class MenuTraversal {
public static void main(String[] args) {
//虚拟点假数据
Menu rootMenu = new Menu(0, -1, "根");
List<Menu> children = new ArrayList<>();
children.add(new Menu(1, 0, "资产"));
children.add(new Menu(2, 0, "监控"));
children.add(new Menu(3, 0, "系统管理"));
children.add(new Menu(4, 1, "机房"));
children.add(new Menu(5, 1, "机柜"));
children.add(new Menu(6, 1, "主机"));
children.add(new Menu(7, 2, "趋势图"));
children.add(new Menu(8, 2, "最新数据"));
children.add(new Menu(9, 3, "用户管理"));
children.add(new Menu(10, 3, "角色管理"));
children.add(new Menu(11, 3, "菜单管理"));
// rootMenu.child = children;
System.out.println(rootMenu);
findChildMenu(rootMenu, children);
System.out.println(JSON.toJSONString(rootMenu));
}
private static void findChildMenu(Menu parentMenu, List<Menu> menus) {
menus.forEach(menu -> {
if (parentMenu.getId() == menu.getPid()) {
parentMenu.child.add(menu);
findChildMenu(menu, menus);
}
});
}
}