背景
物资分类总共有三级分类,分类表category有id、parent_id、rank等字段等字段;
需求
根据三级分类id数组获取其所有父分类。
方法一
- 根据id数组找到这些分类实体;
- 实体数组根据parent_id分组,用一个Map<Long,List>接收;
- 根据这个map的key,即Long型的parent_id,设置parent的子分类;
- 再获取parent的父节点,设置子分类为parent(已到根节点);
- 循环key。
代码:
public List<SourceCategoryEntity> categoryTree(List<Long> categoryIdList){
List<SourceCategoryEntity> categoryEntities = this.getBaseMapper().selectList(new LambdaQueryWrapper<SourceCategoryEntity>()
.in(SourceCategoryEntity::getCategoryId,categoryIdList));
Map<Long,List<SourceCategoryEntity>> collect = categoryEntities.stream().collect(Collectors.groupingBy(SourceCategoryEntity::getParentId));
while(!(collect.size() == 1 && collect.get(0L) != null)){
ArrayList<Long> longs = new ArrayList<>(collect.keySet());
longs.forEach(pid ->{
SourceCategoryEntity parent = getById(pid);
parent.setChildren(collect.get(pid));
List<SourceCategoryEntity> parentList = collect.getOrDefault(parent.getParentId(), new ArrayList<>());
parentList.add(parent);
collect.put(parent.getParentId(),parentList);
collect.remove(pid);
});
}
return collect.getOrDefault(0L,new ArrayList<>());
}
缺点:仅限于有三级分类。
方法二
- 根据id数组找到这些分类实体;
- 实体数组根据parent_id分组,用一个Map<Long,List>接收;
- 循环这个map,设置父节点的属性,递归设置父节点的父节点的属性。
代码:
public List<SourceCategoryEntity> categoryTreeTest(List<Long> categoryIdList) {
List<SourceCategoryEntity> categoryEntities = this.getBaseMapper().selectList(new LambdaQueryWrapper<SourceCategoryEntity>()
.in(SourceCategoryEntity::getCategoryId,categoryIdList));
Map<Long,List<SourceCategoryEntity>> collect = categoryEntities.stream().collect(Collectors.groupingBy(SourceCategoryEntity::getParentId));
List<SourceCategoryEntity> list = new ArrayList<>();
collect.forEach((pid,childlist) -> {
list.add(getFirstCategory(pid,childlist));
});
return list;
}
public SourceCategoryEntity getFirstCategory(Long pid,List<SourceCategoryEntity> childList){
SourceCategoryEntity parent = getById(pid);
if (parent.getParentId() == 0) {
parent.setChildren(childList);
return parent;
}
parent.setChildren(childList);
List<SourceCategoryEntity> parentList = new ArrayList<>();
parentList.add(parent);
return getFirstCategory(parent.getParentId(), parentList);
}
注意:递归里的return只会跳出这次递归,继续执行下次。