实现树形结构数据的方法有很多种,比较常用的有递归。下面我们来实现非递归方式实现树形结构数据。
/**
* @description: 获取分类tree结构数据
* @author 18068
* @date: 2022/12/19 16:45
*/
@Override
public List<GoodsCategory> getCategoryList() {
//查询数据
LambdaQueryWrapper<GoodsCategory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
lambdaQueryWrapper
.select(
GoodsCategory::getCategoryId,
GoodsCategory::getCategoryName,
GoodsCategory::getIconUrl,
GoodsCategory::getCategoryRank,
GoodsCategory::getParentId,
GoodsCategory::getState,
GoodsCategory::getSort
)
.eq(GoodsCategory::getState, StateEnum.OK.getCode());
//数据list
List<GoodsCategory> categoryList = goodsCategoryMapper.selectList(lambdaQueryWrapper);
//定一个map集合
Map<Integer, GoodsCategory> map = new HashMap<>();
//把list集合数据的id作为map集合的key,把此id的这条数据作为map集合的value值
Map<Integer, GoodsCategory> categoryMap = categoryList.stream()
.collect(Collectors.toMap(val -> val.getCategoryId(), val -> val));
//筛选出顶级节点
List<GoodsCategory> rootList = categoryList.stream()
.filter(val -> val.getCategoryRank() == 1).collect(Collectors.toList());
//遍历拼接
categoryList.forEach(val -> {
//找出id==parentId
if (categoryMap.containsKey(val.getParentId())) {
categoryMap.get(val.getParentId()).getChildren().add(val);
}
});
return rootList;
}
结果如下: