java后端树形数据的构造
public List getProviderCategoryInfos() {
ArrayList result = new ArrayList<>();
/1.获取所有数据
LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>();
List list = this.baseMapper.selectList(wrapper);
if (CollUtil.isNotEmpty(list)) {
// 2.将查到的结果通过mapstruct转换ProviderQueryResponseDTO(视项目需要而定)
List providerQueryResponses = categoryConvert.poConvertQueryResponseDTOList(list);
//3.再将子节点的数据转为以parentId为key的map,parentId!=1代表为子节点
Map<Long, List> sonMap = providerQueryResponses.stream()
.filter(p -> Objects.nonNull(p.getProviderCategoryParentId()) && p.getProviderCategoryParentId() != 1).collect(Collectors.groupingBy(ProviderQueryResponseDTO::getProviderCategoryParentId));
//4,过滤出所有根节点(没有父节点的数据)
List rootList = providerQueryResponses.stream().filter(p -> p.getParentId() == 1).collect(Collectors.toList());
//5.遍历父节点数据构造完整树行数据存入result返回
for (ProviderQueryResponseDTO p : rootList) {
p = buildChildren(p, sonMap);
result.add§;
}
}
return result;
}
/**
* 根据父节点进行树形构造
*
* @return {@link ProviderQueryResponseDTO }
* @author lijian
* @date 2023/09/05
*/
public ProviderQueryResponseDTO buildChildren(ProviderQueryResponseDTO root, Map<Long, List> sonMap) {
//如果存在父节点等于当前节点id,子节点继续递归,存入子节点数据
if (CollUtil.isNotEmpty(sonMap) && sonMap.containsKey(root.getProviderCategoryId())) {
List children = sonMap.get(root.getProviderCategoryId());
for (ProviderQueryResponseDTO p : children) {
buildChildren(p, sonMap);
}
root.setChildren(children);
}
return root;
}
树形结构数据的构造
于 2023-09-06 10:58:42 首次发布