Java 后端封装自关联菜单表数据

封装菜单表递归方法 diGuiMenu(),自关联表数据

话不多说,上代码

   /**
     * 封装菜单集合
     * @param rootMenu 角色对应所有菜单
     * @return
     */
    private List<Menu> diGuiMenu(List<Menu> rootMenu) {
//        Map<Integer, List<Menu>> groupByParentMap = menuList.stream().collect(Collectors.groupingBy(Menu::getParentId));
////rootMenu所有菜单的集合
        List<Menu> menuList = new ArrayList<Menu>();
// 先找到所有的一级菜单
        for (int i = 0; i < rootMenu.size(); i++) {
// 一级菜单没有parentId
            if (StringUtils.isEmpty(rootMenu.get(i).getParentId())) {
                menuList.add(rootMenu.get(i));
            }
        }
// 为一级菜单设置子菜单,getChild是递归调用的
        for (Menu menu : menuList) {
            List<Menu> childs = getChild(menu.getId().toString(), rootMenu);
            if (childs != null && childs.size() > 0) {
                menu.setList(childs);
            }
        }
        return menuList;
    }
    private List<Menu> getChild(String id, List<Menu> rootMenu) {
// 子菜单
        List<Menu> childList = new ArrayList<Menu>();
        for (Menu menu : rootMenu) {
// 遍历所有节点,将父菜单id与传过来的id比较
            if (!StringUtils.isEmpty(menu.getParentId().toString())) {
                if ((menu.getParentId() + "").equals(id)) {
                    childList.add(menu);
                }
            }
        }
// 把子菜单的子菜单再循环一遍
        for (Menu menu : childList) {// 没有url子菜单还有子菜单
            if (!StringUtils.isEmpty(menu.getParentId().toString())) {
// 递归
                List<Menu> childs = getChild(menu.getId().toString(), rootMenu);
                if (childs != null && childs.size() > 0) {
                    menu.setList(childs);
                }
            }
        } // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }

参考链接 ——http://www.yayihouse.com/yayishuwu/chapter/1823

源码,是痛苦的,又是快乐的,如果没有这痛苦,也就没有了这快乐!
原文地址:https://www.cnblogs.com/erlongxizhu-03/p/12367895.html