递归实现树结构封装
程序员文章站
2022-07-13 12:52:38
...
简介
作为一名两年的程序猿,每每需要用到递归的都要头疼一番,所以今天就再这里写一个案例,记录一下自己递归实现树结构的封装.
代码实现
1.DataSourceTreeDomain.java用于返回给页面展示
@Data
public class DataSourceTreeDomain {
@ApiModelProperty(value = "ID")
private Long id;
@ApiModelProperty(value = "元数据名称")
private String resourceName;
@ApiModelProperty(value = "父ID")
private Long msgParentId;
@ApiModelProperty(value = "信息资源名称或分类")
private String msgResourceName;
@ApiModelProperty(value = "子树")
List<DataSourceTreeDomain> children = new ArrayList<>();
}
2.方法实现
public List<DataSourceTreeDomain> listTree() {
Iterable<DataSource> dataSourceIterable = dataSourceRepository.findAll();
List<DataSourceTreeDomain> dataSourceTreeDomainList = new ArrayList<>();
Map<Long, List<DataSource>> dataSourceTree = new HashMap<>();
dataSourceIterable.forEach(dataSource -> {
if(dataSource.getMsgParentId() == null){
DataSourceTreeDomain dataSourceTreeDomain = new DataSourceTreeDomain();
BeanUtils.copyProperties(dataSource,dataSourceTreeDomain);
dataSourceTreeDomainList.add(dataSourceTreeDomain);
}else{
List<DataSource> dataSources = dataSourceTree.get(dataSource.getMsgParentId());
if(dataSources == null){
dataSources = new ArrayList<>();
}
dataSources.add(dataSource);
dataSourceTree.put(dataSource.getMsgParentId(),dataSources);
}
});
dataSourceTreeDomainList.forEach(dataSourceTreeDomain -> recursiveDataSource(dataSourceTreeDomain,dataSourceTree));
return dataSourceTreeDomainList;
}
3.封装树结构
private void recursiveDataSource(DataSourceTreeDomain dataSourceTreeDomain, Map<Long, List<DataSource>> dataSourceTree) {
List<DataSource> dataSourceList = dataSourceTree.get(dataSourceTreeDomain.getId());
Optional.ofNullable(dataSourceList).ifPresent(dataSources -> dataSources.forEach(dataSource -> {
DataSourceTreeDomain dataSourceDomain = new DataSourceTreeDomain();
BeanUtils.copyProperties(dataSource,dataSourceDomain);
dataSourceTreeDomain.getChildren().add(dataSourceDomain);
recursiveDataSource(dataSourceDomain,dataSourceTree);
}));
}
效果展示
下一篇: tensorflow 正则化代码