查询出所有菜单并将其组装成父子结构

  public List<PmsCategory> listWithTree() {
        // 1、查出所有分类数据
        List<PmsCategory> categories = baseMapper.selectList(null);
        // 2、将查出的数据组装成父子结构,首先过滤出一级分类,然后对每个一级分类进行子分类组装,此处注意数据库中一定不能有ParentCid为空的数据,不然会报空指针
        return categories.stream().filter(category -> category.getParentCid() == 0)
                //peek 的作用类似forEach() ,不过peek返回的是stream流本身,而forEach则会终结流操作
                .peek(category -> category.setChildren(getChildren(category, categories)))
                // 使用Comparator比较器时只需要传入比较的对象即可
                .sorted(Comparator.comparingInt(o -> (o.getSort() == null ? 0 : o.getSort())))
                .collect(Collectors.toList());
    }

    // 从所有菜单中查出当前菜单的子菜单,层层递归
    private List<PmsCategory> getChildren(PmsCategory target, List<PmsCategory> source) {
        return source.stream().filter(category -> Objects.equals(category.getParentCid(), target.getCatId()))
                .peek(category -> category.setChildren(getChildren(category, source)))
                .sorted(Comparator.comparingInt(o -> (o.getSort() == null ? 0 : o.getSort())))
                .collect(Collectors.toList());
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龙茶清欢

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值