分类繁多,要读取分类并按树型结构展示,需要使用递归方法。
/**
* 查出所有分类及子分类,以树型结构展示接口
*/
@Override
public List<CategoryEntity> listWithTree() {
// 1.查出所有分类
List<CategoryEntity> entities = baseMapper.selectList(null);
// 2.组装树型结构
// 2.1 找到所有的一级分类,使用 arr.stream().filter(obj) 进行过滤
// 收集之前,使用 arr.stream().map(obj) 方法收集子分类列表
List<CategoryEntity> parentList = entities.stream().filter((categoryEntity) -> {
return categoryEntity.getParentCid() == 0;
}).map((categoryEntity)->{
// 递归寻找子分类
categoryEntity.setChildren(getChildren(categoryEntity, entities));
return categoryEntity;
}).sorted((root1, root2)->{
// 菜单排序
return (root1.getSort()==null?0:root1.getSort()) - (root2.getSort()==null?0:root2.getSort());
}).collect(Collectors.toList());
return parentList;
}
/**
* 递归方法获取子分类
* 传入两个参数,一个是当前父节点currentRoot,一个是所有的节点allRoot
*/
private List<CategoryEntity> getChildren(CategoryEntity currentRoot, List<CategoryEntity> allRoot){
// 查找所有记录中父ID等于当前节点ID的记录
List<CategoryEntity> children = allRoot.stream().filter((categoryEntity) -> {
return categoryEntity.getParentCid() == currentRoot.getCatId();
}).map((categoryEntity)->{
// 递归寻找子分类
categoryEntity.setChildren(getChildren(categoryEntity, allRoot));
return categoryEntity;
}).sorted((root1, root2) -> {
// 菜单排序
return (root1.getSort()==null?0:root1.getSort()) - (root2.getSort()==null?0:root2.getSort());
}).collect(Collectors.toList());
return children;
}