多级菜单展示(1)

mac2024-11-02  13

如何将一个list中的对象按照父子菜单包含关系展示?

示例代码:

实体类:

import lombok.*; import java.util.List; @Setter @Getter @ToString @NoArgsConstructor @AllArgsConstructor public class Menu { private int id; private int parentId; private String name; private List<Menu> children; public Menu(int id, int parentId, String name) { this.id = id; this.parentId = parentId; this.name = name; } }

测试类:

import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class SimpleTest2 extends BaseTest{ @Test public void testListToMap(){ List<Menu> menuList = new ArrayList<>(); menuList.add(new Menu(1,0,"后台管理")); menuList.add(new Menu(2,1,"用户管理")); menuList.add(new Menu(3,1,"角色管理")); menuList.add(new Menu(4,1,"菜单管理")); menuList.add(new Menu(5,0,"商品管理")); menuList.add(new Menu(6,5,"商品查询")); menuList.add(new Menu(7,5,"商品添加")); Map<Integer,Menu> menus = new HashMap<>(); //获取一级菜单,这里是后台管理,商品管理添加到menus里 for(Menu menu: menuList){ //parentId = 0 代表父菜单 if(menu.getParentId() == 0){ menus.put(menu.getId(),menu); }else{ continue; } } // 加载二级菜单 for(Menu menu:menuList){ if(menu.getParentId() != 0 && menus.get(menu.getParentId()) != null){ //父节点 Menu parentNode = menus.get(menu.getParentId()); //子节点 Menu childNode = menu; if(parentNode.getChildren() == null){ List<Menu> children = new ArrayList<>(); parentNode.setChildren(children); } parentNode.getChildren().add(childNode); } } // 二级菜单加载完毕 // 迭代打印菜单 for(Integer id: menus.keySet()){ Menu menu = menus.get(id); System.out.println(menu.getName()); if(menu.getChildren() != null){ for(Menu menu1: menu.getChildren()){ System.out.println("\t" + menu1.getName()); } } } } }
最新回复(0)