参数说明
CategoryEntity
实体类getCatId
分类idgetParentCid
父分类idgetParentCid
排序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 集合 |