具体描述:有三级分类菜单,单独查询每级菜单分类都能查到,现在就是第三级分类的菜单有部分的分类查询不出来(navicat能查出来,java出不出来)。
这是单独查询的第三级分类,下面的红框部分用过二级分类查询不到(navicat能查出来)
private List<CategoryEntity> getChildrenList(CategoryEntity root,List<CategoryEntity> all){ List<CategoryEntity> list = new ArrayList<CategoryEntity>(); for (CategoryEntity categoryEntity:all) { if (categoryEntity.getParentCid() == root.getCatId()){ list.add(categoryEntity); } } //这里是是使用匿名内部类来完成的 Collections.sort(list, new Comparator<CategoryEntity>() { @Override public int compare(CategoryEntity o1, CategoryEntity o2) { //指定比较规则,按照首字母降序来排列 return o2.getSort()-o1.getSort(); } }); return list; }
@Override public List<CategoryEntity> listCategory() { List<CategoryEntity> categoryEntityList = new ArrayList<>(); List<CategoryEntity> scendCategoryEntityList = categoryList(2); List<CategoryEntity> thirdCategoryEntityList = categoryList(3); //1、查出所有分类 List<CategoryEntity> entities = baseMapper.selectList(null); System.out.println("获取到的三级分类---》" + thirdCategoryEntityList); for (CategoryEntity categoryEntity:entities) { if (categoryEntity.getParentCid() == 0){//找到一级菜单 List<CategoryEntity> scendChildrenList = getChildrenList(categoryEntity, scendCategoryEntityList); for (CategoryEntity scendChildre:scendChildrenList) { scendChildre.setChildren(getChildrenList(scendChildre,thirdCategoryEntityList)); } categoryEntity.setChildren(scendChildrenList); categoryEntityList.add(categoryEntity); } } return categoryEntityList; }
上面是一种方法
下面又是一种:
//递归查找所有菜单的子菜单 private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){ List<CategoryEntity> children = all.stream().filter(categoryEntity -> { return categoryEntity.getParentCid() == root.getCatId(); }).map(categoryEntity -> { //1、找到子菜单 categoryEntity.setChildren(getChildrens(categoryEntity,all)); return categoryEntity; }).sorted((menu1,menu2)->{ //2、菜单的排序 return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort()); }).collect(Collectors.toList()); return children; }
@Override public List<CategoryEntity> listWithTree() { //1、查出所有分类 List<CategoryEntity> entities = baseMapper.selectList(null); //2、组装成父子的树形结构 //找到所有的一级分类 List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0 ).map((menu)->{ menu.setChildren(getChildrens(menu,entities)); return menu; }).sorted((menu1,menu2)->{ return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort()); }).collect(Collectors.toList()); return level1Menus; }