@Override标签:return,Stream,树结构,List,查询,menu2,menu1,null,getSort From: https://www.cnblogs.com/sensenh/p/16922007.html
public List<CategoryEntity> listWithTree() {
//1、查询所有的分类数据
List<CategoryEntity> entities = categoryDao.selectList(null);
//2、组装成父子的树形结构
//2.1、找到所有的一级分类
List<CategoryEntity> level1Menus = entities.stream().filter(s -> {
boolean b = false;
if (s.getParentCid() != null) {
b = s.getParentCid() == 0;
}
return b;
}).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;
}
/**
* 递归获取菜单类别的子节点
* @param root 父节点
* @param all 所有类别数据
* @return
*/
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;
}