10.业务功能实现---商品服务三级分类树形API
作者:互联网
1.商品服务三级分类树形API
- 实体类,添加属性
@Data
@TableName("pms_category")
public class CategoryEntity implements Serializable {
private static final long serialVersionUID = 1L;
// ...
/**
* 子分类数据
*/
@TableField(exist = false)
private List<CategoryEntity> children;
}
- 对数据进行分类的方法,组成树形结构:
public List<CategoryEntity> getListToTree() {
//1.获取所有分类数据
List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
//2.组装成树形结构
//2.1).先找到所有的一级分类,然后继续设置分类下的子分类,最后排序,归约
List<CategoryEntity> firstLevelMenu = categoryEntities.stream()
.filter(categoryEntity -> categoryEntity.getParentCid() == 0)
.map((menu) -> {
menu.setChildren(getChildren(categoryEntities, menu));
return menu;
})
.sorted((menu1, menu2) -> {
return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
}).collect(Collectors.toList());
return firstLevelMenu;
}
/**
* 递归设置各级子菜单
*
* @param all 所有的分类数据
* @param root 一级菜单
* @return
*/
private List<CategoryEntity> getChildren(List<CategoryEntity> all, CategoryEntity root) {
List<CategoryEntity> children = all.stream()
.filter(categoryEntity -> categoryEntity.getParentCid() == root.getCatId())
.map(categoryEntity -> {
//递归设置子菜单
categoryEntity.setChildren(getChildren(all, categoryEntity));
return categoryEntity;
}).sorted((menu1, menu2) -> {
return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
}).collect(Collectors.toList());
return children;
}
标签:10,return,List,categoryEntity,---,API,menu2,menu1,getSort 来源: https://www.cnblogs.com/lailix/p/16649171.html