获取树形结构,第一反应是递归,其实用遍历也可以做,更优雅
public List<FolderInfoVO> searchTree() {
List<FolderInfoVO> folderInfos = folderInfoMapper.searchAll();
//将非根节点的folder按照parId分组,key是parId,value是parId相同的folder的集合
Map<Integer, List<FolderInfoVO>> listMap = folderInfos.stream()
.filter(folder -> folder.getParId() != 0)
.collect(Collectors.groupingBy(FolderInfoVO::getParId));
//给每个folder设置子folder
folderInfos.forEach(folder -> folder.setChildren(listMap.get(folder.getId())));
//过滤掉parId不是0的folder
List<FolderInfoVO> vos = folderInfos.stream()
.filter(folder -> folder.getParId() == 0)
.collect(Collectors.toList());
return vos;
}
对应的文件夹VO对象结构
@Data
public class FolderInfoVO {
private Integer id;
private String folderName;
private Integer parId;
private List<FolderInfoVO> children;
}
思路来源:抖音:程序员蜗牛