springboot 递归的实现
1.首先理清楚 递归就是根据查询的根节点List数据进行调用递归方法
2.递归方法则是通过传入的根节点数据的id来作为子集的prentId为条件进行查询,如果查询不为空则把子集进行遍历放入到实体类中的children
// 查询所有根节点数据,然后将根节点数据进行递归实现查询出所有的节点
List<IndicatorLibrary> indicatorLibraries = indicatorLibraryService.list(new QueryWrapper<IndicatorLibrary>().eq("prent_id", "0"));
List<IndicatorLibrary> indicatorLibraries1 = RecursiveSubset(indicatorLibraries);
IPage<IndicatorLibrary> pageList = new Page<>(pageNo, pageSize, indicatorLibraries1.size());
pageList.setRecords(indicatorLibraries1);
return Result.OK(pageList);
RecursiveSubset递归方法
public List<IndicatorLibrary> RecursiveSubset(List<IndicatorLibrary> indicatorLibraries) {
List<IndicatorLibrary> subsetIndicatorLibraries = new ArrayList<>();
for (IndicatorLibrary indicatorLibrary : indicatorLibraries) {
// 查询所有的根节点数据
List<IndicatorLibrary> list = indicatorLibraryService.list(new LambdaQueryWrapper<IndicatorLibrary>().eq(IndicatorLibrary::getPrentId, indicatorLibrary.getId()));
if (ObjectUtils.isNotEmpty(list)) {
List<IndicatorLibrary> children = new ArrayList<>();
for (IndicatorLibrary library : list) {
children.addAll(RecursiveSubset(Collections.singletonList(library))); // 递归调用并获取结果
}
indicatorLibrary.setChildren(children); // 将所有子节点合并到一个列表中,并设置为当前节点的子节点
subsetIndicatorLibraries.add(indicatorLibrary); // 将当前节点添加到结果列表中
} else {
subsetIndicatorLibraries.add(indicatorLibrary); // 处理空列表的情况
}
}
return subsetIndicatorLibraries;
}
优化之后的代码
public List<IndicatorLibrary> recursiveSubset(List<IndicatorLibrary> indicatorLibraries) {
List<IndicatorLibrary> subsetIndicatorLibraries = new ArrayList<>();
Set<String> parentIds = indicatorLibraries.stream().map(IndicatorLibrary::getId).collect(Collectors.toSet());
List<IndicatorLibrary> children = indicatorLibraryService.list(new LambdaQueryWrapper<IndicatorLibrary>().in(IndicatorLibrary::getPrentId, parentIds));
Map<String, List<IndicatorLibrary>> childrenMap = children.stream().collect(Collectors.groupingBy(IndicatorLibrary::getPrentId));
for (IndicatorLibrary indicatorLibrary : indicatorLibraries) {
List<IndicatorLibrary> childList = childrenMap.get(indicatorLibrary.getId());
if (childList != null && !childList.isEmpty()) {
indicatorLibrary.setChildren(recursiveSubset(childList));
}
subsetIndicatorLibraries.add(indicatorLibrary);
}
return subsetIndicatorLibraries;
}