递归查询方法

递归查询方法

    /**
     * 获取树形结构的商品数据
     * @return
     */
    @Override
    public  List<CategoryEntity> listWithTree() {
        //1.获取所有的商品分类数据
        List<CategoryEntity> rootCategoryList = baseMapper.selectList(null);
        //2.组装成父子树形结构
        List<CategoryEntity> list = rootCategoryList.stream()
                //过滤出一级分类商品
                .filter(categoryEntity -> categoryEntity.getParentCid().longValue() == 0 )
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity,rootCategoryList));
                    return categoryEntity;
                })
                .sorted((menu1,menu2)->{return  (menu1.getSort()==null ? 0 : menu1.getSort()) -
                        (menu2.getSort() == null?0:menu2.getSort());})
                .collect(Collectors.toList());
        return list;
    }

    /**
     * 递归查询出所有的子菜单
     * @param root
     * @param allCategories
     * @return
     */
    private List<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> allCategories)
    {
        List<CategoryEntity> children = allCategories.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().longValue() == root.getCatId().longValue())
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity, allCategories));
                    return categoryEntity;
                }) .sorted((menu1, menu2) -> {
                    return (menu1.getSort()==null ? 0 : menu1.getSort())  -
                            (menu2.getSort() == null?0:menu2.getSort());})
                .collect(Collectors.toList());
        return children;
    }
posted @ 2022-08-25 20:52  肖恩雷  阅读(73)  评论(0编辑  收藏  举报