赞
踩
@Data
public class Category {
private Integer id;
private Integer parentId;
private String name;
private Boolean status;
private Integer sortOrder;
private Date createTime;
private Date updateTime;
}
@Data
public class CategoryVo {
private Integer id;
private Integer parentId;
private String name;
private Integer sortOrder;
private List<CategoryVo> subCategories;
}
@Override
public ResponseVo<List<CategoryVo>> selectAll() {
//查询商品分类集合
List<Category> categories = categoryMapper.selectAll();
//获取顶级分类集合
//实现jdk8的 lambda + stream
List<CategoryVo> categoryVoList=categories.stream()
.filter(x->x.getParentId().equals(ROOT_PARENT_ID)) //判断是否为父级分类
.map(x-> category2CategoryVo(x)) //对象copy
.sorted(Comparator.comparing(CategoryVo::getSortOrder).reversed()) //排序
.collect(Collectors.toList()); //收集到集合中
//查询子目录
findSubCategory(categoryVoList, categories);
return ResponseVo.success(categoryVoList);
}
private CategoryVo category2CategoryVo(Category category) {
CategoryVo categoryVo = new CategoryVo();
BeanUtils.copyProperties(category, categoryVo);//spring 自带copy工具方法
return categoryVo;
}
/**
* 查询子级分类
* @param categoryVoList 父级分类集合
* @param categories 所以的商品分类集合
*/
private void findSubCategory(List<CategoryVo> categoryVoList, List<Category> categories) {
for (CategoryVo categoryVo : categoryVoList) {
List<CategoryVo> subCategoryVoList = new ArrayList<>();
for (Category category : categories) {
//如果查到内容,设置subCategory, 继续往下查
if (categoryVo.getId().equals(category.getParentId())) {
CategoryVo subCategoryVo = category2CategoryVo(category);
subCategoryVoList.add(subCategoryVo);
}
subCategoryVoList.sort(Comparator.comparing(CategoryVo::getSortOrder).reversed());//对根据对象字段sortOrder对集合进行排序(不要求排序的忽略)
categoryVo.setSubCategories(subCategoryVoList);
//递归查询(查询当前分类是否还有子级)
findSubCategory(subCategoryVoList, categories);
}
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。