问题:
商品分类、角色分类等需要进行“父子”分类的场景下,大多需要后台查询到数据后以树形结构返回给前端;
之前公司关于分类控制在三级以内,所以在分类处理上代码写的比较死;分类层级达到四级、五级之后扩展起来就显得很low,因此使用递归方式来进行分类处理,依旧返回树形结构。
旧代码:
public List<CategoryVO> shopCategoryList(Long shopId) {
//查出所有的分类信息
List<CategoryVO> list = categoryMapper.listByShopIdAndParenId(shopId, null);
//根据分类级别分组
Map<Integer, List<CategoryVO>> categoryMap = list.stream().collect(Collectors.groupingBy(CategoryVO::getLevel));
//获取二级分类
List<CategoryVO> secondCategories =
categoryMap.get(CategoryLevel.SECOND.value());
if (Objects.equals(shopId, Constant.PLATFORM_SHOP_ID)) {
//获取三级分类
List<CategoryVO> thirdCategories = categoryMap.get(CategoryLevel.THIRD.value());
//给二级分类设置三级子分类
setChildCategory(secondCategories, thirdCategories);
}
//一级分类
List<CategoryVO> firstCategories = categoryMap.get(CategoryLevel.First.value());
//给一级分类设置二级子分类
setChildCategory(firstCategories, secondCategories);
return firstCategories;
}
//设置子分类
private void setChildCategory(List<CategoryVO> categories, List<CategoryVO> childCategories) {
if (CollUtil.isEmpty(categories) || CollUtil.isEmpty(childCategories)) {
return;
}
Map<Long, List<CategoryVO>> secondCategoryMap = childCategories.stream().collect(Collectors.groupingBy(CategoryVO::getParentId));
for (CategoryVO category : categories) {
category.setCategories(secondCategoryMap.get(category.getCategoryId()));
}
}
新的方式:
使用递归解决层级不明确问题
@Override
public List<PmsCategoryEntity> listWithTree() {
//查询所有分类
List<PmsCategoryEntity> entities = baseMapper.selectList(null);
//获取当前分类下的子分类 new ComparatorMe()是自定义的比较器,可以根据自己的需求定制
List<PmsCategoryEntity> entitiesTree = entities
.stream()
.filter((PmsCategoryEntity) -> PmsCategoryEntity.getParentCid() == 0)
.map((menu)->{
menu.setChildren(getChildren(menu,entities));
return menu;
})
.sorted(Comparator.comparing(PmsCategoryEntity::getSort,Comparator.nullsLast(new ComparatorMe())))
.collect(Collectors.toList());
entitiesTree.forEach((temp)-> temp.setIcon("icon"));
return entitiesTree;
}
/**
* 设置children 这里使用到的是comparaotr的自然比较器
*/
private List<PmsCategoryEntity> getChildren(PmsCategoryEntity root,List<PmsCategoryEntity> all){
List<PmsCategoryEntity> childrens = all.stream()
.filter((PmsCategoryEntity) -> PmsCategoryEntity.getParentCid() == root.getCatId())
.map((menu) -> {
menu.setChildren(getChildren(menu, all));
return menu;})
.sorted(Comparator.comparing(PmsCategoryEntity::getSort,Comparator.nullsLast(Comparator.naturalOrder())))
.collect(Collectors.toList());
return childrens;
}