树迭代循环 java8 用lambda表达式

场景 同一个表 父和子 共存 ParentId 字段使用 一般用于 菜单或者省市区 使用

直接上代码 实体类 不提供 详解 懂得自然懂:

    public CommonResult<List<GoodsCategoryTreeDTO>> goodsCategoryTree() {
QueryWrapper<ItemCategory> queryWrapper = new QueryWrapper<ItemCategory>().eq("status", 1).orderByAsc("sort");
List<ItemCategory> categoryEntities = itemCategoryService.list(queryWrapper);
//1.先找一级分类 categoryEntity.getParentId() == 0L
//2.查询一级分类下的子类
List<GoodsCategoryTreeDTO> levelCategory = categoryEntities.stream().
filter(categoryEntity -> categoryEntity.getParentId() == 0L).
// sorted(Comparator.comparing(ItemCategory::getMenuOrder)).
//保存当前分类的子分类
map(category -> {
//当前分类的子分类收集并返回
GoodsCategoryTreeDTO categoryTreeRespDTO = new GoodsCategoryTreeDTO();
BeanUtils.copyProperties(category, categoryTreeRespDTO);
categoryTreeRespDTO.setChildren(listSubMenu(category, categoryEntities));
return categoryTreeRespDTO;
}).collect(Collectors.toList());
return CommonResult.success(levelCategory);
}

public List<GoodsCategoryTreeDTO> listSubMenu(ItemCategory root, List<ItemCategory> all) {
List<GoodsCategoryTreeDTO> children = all.stream().
filter(e -> e.getParentId().equals(root.getId())).
map(categoryEntity -> {
//当前分类的子分类收集并返回
GoodsCategoryTreeDTO categoryTreeRespDTO = new GoodsCategoryTreeDTO();
BeanUtils.copyProperties(categoryEntity, categoryTreeRespDTO);
categoryTreeRespDTO.setChildren(listSubMenu(categoryEntity, all));
return categoryTreeRespDTO;
}).collect(Collectors.toList());
return children;
}
posted @ 2022-03-09 17:22  伤心的鸽子  阅读(137)  评论(0编辑  收藏  举报