详细记录java流式编程,运用streamAPI filter,map,collect方法
结合实战举例记录这些运用
业务逻辑为 多级分类 比如 一级分类为 手机 二级分类 就有华为手机 苹果手机
三级分类就有 P系列 mate系列 nova系列 iphone系列 等等
@Override
public List<CategoryEntity> listWithTree() {
//1.查出所有分类
List<CategoryEntity> entities = baseMapper.selectList(null);
//2.组装成父子树形结构
//2.1 找到所有一级分类 最顶部的父分类
List<CategoryEntity> level1Menus = entities.stream().filter((categoryEntity) -> {
return categoryEntity.getParentCid() == 0;//filter中的箭头函数来筛选,在我数据库中ParentCid == 0 的是一级分类
}).map((menu)->{
menu.setChildren(getChildren(menu,entities)); //map中对每一个实体对象来做映射,找到他们的子分类,见下方自定义方法
return menu;
}).sorted((menu1,menu2)->{
return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());//解决空指针异常
}).collect(Collectors.toList());//将结果转化为list类型
return level1Menus;
}
//递归查找所有菜单的子菜单
private List<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> all){
List<CategoryEntity> children = all.stream().filter((entity) -> {
return entity.getParentCid() == root.getCatId();
}).sorted((menu1, menu2) -> {
return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());//解决空指针异常
}).map((entity) -> {
//继续递归找子菜单
entity.setChildren(getChildren(entity, all)); //继续调用本方法,递归往下找
return entity;
}).collect(Collectors.toList());
return children;
}