栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

如何通过java8Stream给三级菜单分类

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何通过java8Stream给三级菜单分类

如何通过java8Stream给三级菜单分类

数据库中返回所有的一级二级三级菜单,然后通过分类返回给前端

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.io.Serializable;
import java.util.List;


@Data
@TableName("pms_category")
public class CategoryEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	
	@TableId
	private Long catId;
	
	private String name;
	
	private Long parentCid;
	
	private Integer catLevel;
	
	@TableLogic(value = "1",delval = "0")
	private Integer showStatus;
	
	private Integer sort;
	
	private String icon;
	
	private String productUnit;
	
	private Integer productCount;

	//添加的属性,非数据库字段
	@TableField(exist = false)
	private List children;

}
@Override
    public List listWithTree() {
        //1、查询出所有的分类(select * from pms_category)
        List entities = baseMapper.selectList(null);

        //2、组装成树形结构
        //2.1 查询出所有的一级菜单
        List level1 = entities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(0L))
                //映射 改变每个菜单的children信息
                .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 level1;
    }

    
    private List getChildren(CategoryEntity root, List all){
        List children = all.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity,all));
                    return categoryEntity;
                })
                .sorted((menu1, menu2) ->
                        (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort())
                )
                //.sorted(Comparator.comparing(CategoryEntity::getSort))
                .collect(Collectors.toList());
        return children;
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1004326.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号