java实现tree树形结构
树节点遍历工具类:
1 @UtilityClass 2 public class TreeUtil { 3 /** 4 * 两层循环实现建树 5 * 6 * @param treeNodes 传入的树节点列表 7 * @return 8 */ 9 public <T extends TreeNode> List<T> bulid(List<T> treeNodes, Object root) { 10 11 List<T> trees = new ArrayList<>(); 12 13 for (T treeNode : treeNodes) { 14 15 if (root.equals(treeNode.getParentId())) { 16 trees.add(treeNode); 17 } 18 19 for (T it : treeNodes) { 20 if (it.getParentId() == treeNode.getId()) { 21 if (treeNode.getChildren() == null) { 22 treeNode.setChildren(new ArrayList<>()); 23 } 24 treeNode.add(it); 25 } 26 } 27 } 28 return trees; 29 } 30 31 /** 32 * 使用递归方法建树 33 * 34 * @param treeNodes 35 * @return 36 */ 37 public <T extends TreeNode> List<T> buildByRecursive(List<T> treeNodes, Object root) { 38 List<T> trees = new ArrayList<T>(); 39 for (T treeNode : treeNodes) { 40 if (root.equals(treeNode.getParentId())) { 41 trees.add(findChildren(treeNode, treeNodes)); 42 } 43 } 44 return trees; 45 } 46 47 /** 48 * 递归查找子节点 49 * 50 * @param treeNodes 51 * @return 52 */ 53 public <T extends TreeNode> T findChildren(T treeNode, List<T> treeNodes) { 54 for (T it : treeNodes) { 55 if (treeNode.getId() == it.getParentId()) { 56 if (treeNode.getChildren() == null) { 57 treeNode.setChildren(new ArrayList<>()); 58 } 59 treeNode.add(findChildren(it, treeNodes)); 60 } 61 } 62 return treeNode; 63 } 64 }
树模型:
1 @Data 2 public class TreeNode { 3 protected int id; 4 protected int parentId; 5 protected String name; 6 protected List<TreeNode> children = new ArrayList<TreeNode>(); 7 8 public void add(TreeNode node) { 9 children.add(node); 10 } 11 }
部门树:
1 @Data 2 @EqualsAndHashCode(callSuper = true) 3 public class DeptTree extends TreeNode { 4 private String name; 5 }
构建部门树方法:
1 public List<DeptTree> getDeptTree(List<SysDept> depts) { 2 List<DeptTree> treeList = depts.stream() 3 .filter(dept -> !dept.getDeptId().equals(dept.getParentId())) 4 .map(dept -> { 5 DeptTree node = new DeptTree(); 6 node.setId(dept.getDeptId()); 7 node.setParentId(dept.getParentId()); 8 node.setName(dept.getName()); 9 return node; 10 }).collect(Collectors.toList()); 11 return TreeUtil.bulid(treeList, 0); 12 }