@Data public class Tree { private Integer id; private String name; private Integer age; private String sex; private Integer parentId; private List<Tree> children; public String getId() { if (this.id == null) { return null; } else { return this.id; } } public String getParentId() { if (this.parentId == null) { return null; } else { return this.parentId; } } public void setChildTreeList(List<Tree> treeList) { this.children = treeList; } }
@Data public class TreeBuildFactory<T> { //顶级节点的父节点id(默认-1) private Integer rootParentId = -1; public TreeBuildFactory() {} public TreeBuildFactory(Integer rootParentId) { this.rootParentId = rootParentId; } //传过来一个List集合 public List<T> treeBuild(List<T> treeList) { //将每个节点的构造一个子树 for (T tree : treeList) { this.buildChildTreeList(treeList, tree, new ArrayList<>()); } //只保留上级是根节点的节点,也就是只留下所有一级节点 ArrayList<T> results = new ArrayList<>(); for (T tree : treeList) { if (tree.getParentId().equals(rootParentId)) { results.add(tree); } } return results; } //获取树形集合的主要循环体 private void buildChildTreeList(List<T> treeList, T tree, List<T> list) { if (treeList == null || tree == null) { return; } //获取下一级的集合 List<T> childTreeList = getChildTreeList(treeList, tree); if (childTreeList.size() > 0) { for (T childTreeListItem : childTreeList) { buildChildTreeList(treeList, childTreeListItem, new ArrayList<>()); } } list.addAll(childTreeList); tree.setChildTreeList(list); } //获取下一级的集合 private List<T> getChildTreeList(List<T> treeList, T tree) { List<T> childTreeList = new ArrayList<>(); for (T treeListItem : treeList) { if (treeListItem.getParentId().equals(tree.getId())) { childTreeList.add(treeListItem); } } return childTreeList; } }