如何通过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;
/**
* 商品三级分类
* @author cls
*/
@Data
@TableName("pms_category")
public class CategoryEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 分类id
*/
@TableId
private Long catId;
/**
* 分类名称
*/
private String name;
/**
* 父分类id
*/
private Long parentCid;
/**
* 层级
*/
private Integer catLevel;
/**
* 是否显示[0-不显示,1显示]
*/
@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<CategoryEntity> children;
}
@Override
public List<CategoryEntity> listWithTree() {
//1、查询出所有的分类(select * from pms_category)
List<CategoryEntity> entities = baseMapper.selectList(null);
//2、组装成树形结构
//2.1 查询出所有的一级菜单
List<CategoryEntity> 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;
}
/**
* 递归查找出所有的子菜单
* @param root 当前菜单
* @param all 所有的菜单
* @return
*/
private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all){
List<CategoryEntity> 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;
}