Java使用stream递归处理菜单树形结构

Java使用stream递归处理菜单树形结构

参数说明

  • CategoryEntity 实体类
  • getCatId 分类id
  • getParentCid 父分类id
  • getParentCid 排序
  • getChildren 子分类集合

操作步骤

在 Java 实体类中,需要添加一个属性,方便存储子级结构

	/**子分类*/
	@TableField(exist = false) //注解:非数据库字段
	private List<CategoryEntity> children;

代码实现

public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> entities = this.baseMapper.selectList(null);
        //2.组装父子树形结构

        //2.1先查询所有一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
                //标识为0
                categoryEntity.getParentCid() == 0
        ).map((menu) -> {
            menu.setChildren(getChildren(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;
    }

    //递归查找所有菜单的子菜单方法
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {

        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return root.getCatId().equals(categoryEntity.getParentCid());
        }).map(categoryEntity -> {
            //找到子菜单
            categoryEntity.setChildren(getChildren(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //菜单排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

展示效果

在这里插入图片描述

Stream接口

方法简述
filter过滤当前流中的每一项数据,只接收Boolean结果只保留结果返回true的项
map输入流中的每个项调用,并生成一个结果值,该结果值返回至stream
sorted以自然序或着自定义Comparator 接口排序规则来排序一个流
collect把处理结果收集成一个 List 集合
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值