数据量太大时建议不要使用此方法
/**
* 使用递归方法建树
* @param
* @return
*/
public static List<AreaInfo> buildByRecursive(List<AreaInfo> testEntities) {
List<AreaInfo> trees = new ArrayList<>();
for (AreaInfo testEntity : testEntities) {
if ("".equals(testEntity.getParentId()) || testEntity.getParentId() == null ) {
trees.add(findChildren(testEntity,testEntities));
}
}
return trees;
}
/**
* 递归查找子节点
* @param
* @return
*/
public static AreaInfo findChildren(AreaInfo testEntity,List<AreaInfo> testEntitys) {
for (AreaInfo projectBasicInfoDTO2 : testEntitys) {
if(testEntity.getId().equals(projectBasicInfoDTO2.getParentId())) {
if(testEntity.getChildren() == null) {
testEntity.setChildren(new ArrayList<>());
}
//是否还有子节点,如果有的话继续往下遍历,如果没有则直接返回
testEntity.getChildren().add(findChildren(projectBasicInfoDTO2,testEntitys));
}
}
return testEntity;
}
实体类:
public class AreaInfo {
private Integer id;
private String name;
private Integer parentId;
private List<AreaInfo> children;