public class TreeUtils { /** * 使用递归方法建树 * @param treeNodes * @return */ public static List<ProjectBasicInfoDTO> buildByRecursive(List<ProjectBasicInfoDTO> projectBasicInfoDTOs) { List<ProjectBasicInfoDTO> trees = new ArrayList<ProjectBasicInfoDTO>(); for (ProjectBasicInfoDTO projectBasicInfoDTO : projectBasicInfoDTOs) { if ("".equals(projectBasicInfoDTO.getpId()) || projectBasicInfoDTO.getpId() == null ) { trees.add(findChildren(projectBasicInfoDTO,projectBasicInfoDTOs)); } } return trees; } /** * 递归查找子节点 * @param treeNodes * @return */ public static ProjectBasicInfoDTO findChildren(ProjectBasicInfoDTO projectBasicInfoDTO,List<ProjectBasicInfoDTO> projectBasicInfoDTOs) { for (ProjectBasicInfoDTO projectBasicInfoDTO2 : projectBasicInfoDTOs) { if(projectBasicInfoDTO.getId().equals(projectBasicInfoDTO2.getpId())) { if(projectBasicInfoDTO.getChildren() == null) { projectBasicInfoDTO.setChildren(new ArrayList<ProjectBasicInfoDTO>()); } //是否还有子节点,如果有的话继续往下遍历,如果没有则直接返回 projectBasicInfoDTO.getChildren().add(findChildren(projectBasicInfoDTO2,projectBasicInfoDTOs)); } } return projectBasicInfoDTO; } }