package com.admin.manager.storeService.util; import com.admin.manager.storeService.entity.Menu; import java.util.ArrayList; import java.util.List; /** * @author m * @date 2019/12/16 */ public class TreeUtil { /** * 获取菜单树 * @param menus 所有菜单 * @return */ public static List<Menu> menuTree(List<Menu> menus) { //返回的菜单树 List<Menu> rootMenus = new ArrayList<>(); for (Menu menu : menus) { //pid(上级Id)为0的是根菜单 if ("0".equals(menu.getPid())) { rootMenus.add(menu); } } //遍历,找到二级菜单(根菜单的id和所有菜单中的pid比较) for (Menu rootMenu : rootMenus) { List<Menu> child = getChild(String.valueOf(rootMenu.getId()), menus); rootMenu.setChildren(child); } return rootMenus; } /** * 递归获取下级菜单 * @param pid 上级Id * @param menus 所有菜单 * @return */ public static List<Menu> getChild(String pid, List<Menu> menus) { //子菜单列表 List<Menu> childList = new ArrayList<>(); for (Menu menu : menus) { if (pid.equals(menu.getPid())) { childList.add(menu); } } //遍历 递归获取子菜单的子菜单 for (Menu menu : childList) { List<Menu> child = getChild(String.valueOf(menu.getId()), menus); menu.setChildren(child); } //递归出口 childList长度为0 if (childList.size() == 0) { return new ArrayList<>(); } return childList; } }
|