
public List<CategoryEntity> listWithTree() {
//1查询所有的分类
List<CategoryEntity> entities = baseMapper.selectList(null);
//2组装成父子的树形结构
//--找到所有的一级分类
List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity -> {
return categoryEntity.getParentCid() == 0;
}).map((menu) -> {
//生成子菜单
menu.setChildren(getChildrens(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> getChildrens(CategoryEntity root,List<CategoryEntity> all){
List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
return categoryEntity.getParentCid() == root.getCatId();
}).map(categoryEntity -> {
//查找子菜单
categoryEntity.setChildren(getChildrens(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;
}
//实体
/**
* 分类id
*/
@TableId
private Long catId;
/**
* 分类名称
*/
private String name;
/**
* 父分类id
*/
private Long parentCid;
/**
* 层级
*/
private Integer catLevel;
/**
* 是否显示[0-不显示,1显示]
*/
private Integer showStatus;
/**
* 排序
*/
private Integer sort;
/**
* 图标地址
*/
private String icon;
/**
* 计量单位
*/
private String productUnit;
/**
* 商品数量
*/
private Integer productCount;
@TableField(exist = false )
private List<CategoryEntity> children;
结果:

该篇博客详细介绍了如何通过Java代码构建一个包含层级关系的分类树,并进行排序。首先从数据库中查询所有分类,然后通过stream过滤出一级分类,为每个一级分类递归获取其子分类,并根据排序字段进行排序。最后返回构造好的树形结构。这种方法适用于组织具有层级关系的数据,如网站导航菜单或文件系统目录。
5907

被折叠的 条评论
为什么被折叠?



