本文详细概述了运行的整体过程以及实现的代码,文章内容持续更新中,如果中文描述过程有错误的请各位指出来,让大家一起学习。
@Override
public List<CategoryEntity> listWithTree() {
//使用categoryDao.selectList();也是可以的 他得CategoryDao中也继承了baseMapper
//因为本类继承了serviceImpl 。他的泛型中有baseMapper也可以直接使用
//1.此出功能查出所有分类,selectList查询所有,括号中表示不需要任何条件查询所有
List<CategoryEntity> entities = baseMapper.selectList(null);
//2.组装成父子的树形结构
//2.1找到所有一级分类
List<CategoryEntity> level1Menus = entities.stream().filter((categoryEntity) -> { //entities获取数据,categoryEntity是每一个数据需要过滤得元素。filter表示过滤器
return categoryEntity.getParentCid() == 0; //获取categoryEntity中得第一个数据父id是否等于0,等于0得会全部返回存在这里level1Menus中。此时第一个数据(parentCid是0 {图书})往下走
}).map((menu)->{ //menu表示菜单 level1Menus值会传到menu中,此时有了图书第一个菜单,这是一个父分类。 Tip:map可以将每一个菜单改变
menu.setChildren(getChildrens(menu,entities));//然后再把当前(menu第一个菜单 图书)父类的子分类保存进去。 Tip: setChildren是自己写的一个实现具体功能的方法
return menu;//保存结束之后将当前菜单返回到level1Menus中
}).sorted((menu1,menu2)->{
return (menu1.getSort()==null?0:menu1.getSort())- (menu2.getSort()==null?0: menu2.getSort());
}).collect(Collectors.toList());//最终(collect)收集成一个集合
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 -> {
//1找到子菜单
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;
}
}