java递归生成菜单树(递归找)

public List findTree() {
         //所有的菜单
         List menuList = menuServiceImpl.selectByExample(null);
         List respList = new ArrayList<>();  // respList 装最后返回的结果
         // 先找到所有的一级菜单
         for (Menu value : menuList) {
             //一级菜单parentId=0;
             if (value.getPid() == 0) {
                 respList.add(value);
             }
         }

         // 遍历一级菜单,开始找子菜单
         for (Menu menu : respList) {
             Object childlist = getChild(menu.getId(), menuList);
             menu.setChildren(childlist);
         }
         return respList;
     }


     /**
      * 递归查找子菜单
      * id 当前菜单id
      * menuList  所有的菜单
      */
     private Object getChild(int id, List menuList) {
         // 找二级子菜单
         List childList = new ArrayList<>();
         for (Menu menu : menuList) {
             // 遍历所有菜单,将父菜单id与传过来的id比较,如果相等就是该父菜单下的子菜单
             if (menu.getPid() == id) {
                 childList.add(menu);
             }
         }
         // 把子菜单的子菜单再循查找子菜单
         for (Menu menu : childList) {
             Object obj = getChild(menu.getId(), menuList);
             menu.setChildren(obj);
         }

         return childList;
     }

 

你可能感兴趣的:(树形)