TreeUtils生成树形结构
TreeNode
用来表示每个树节点的抽象,即需要生成树的对象需要实现此接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
public interface TreeNode<T> {
T id();
T parentId();
boolean root();
void setChildren(List<? extends TreeNode<T>> children);
List<? extends TreeNode<T>> getChildren(); }
|
TreeUtils
用来生成树形结构,以及获取所有叶子节点等操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| public class TreeUtils {
public static <T extends TreeNode<?>> List<T> generateTrees(List<T> nodes) { List<T> roots = new ArrayList<>(); for (Iterator<T> ite = nodes.iterator(); ite.hasNext(); ) { T node = ite.next(); if (node.root()) { roots.add(node); ite.remove(); } }
roots.forEach(r -> { setChildren(r, nodes); }); return roots; }
@SuppressWarnings("all") public static <T extends TreeNode> void setChildren(T parent, List<T> nodes) { List<T> children = new ArrayList<>(); Object parentId = parent.id(); for (Iterator<T> ite = nodes.iterator(); ite.hasNext(); ) { T node = ite.next(); if (Objects.equals(node.parentId(), parentId)) { children.add(node); ite.remove(); } } if (children.isEmpty()) { return; } parent.setChildren(children); children.forEach(m -> { setChildren(m, nodes); }); }
public static <T extends TreeNode<?>> List<T> getLeafs(T parent) { List<T> leafs = new ArrayList<>(); fillLeaf(parent, leafs); return leafs; }
@SuppressWarnings("all") public static <T extends TreeNode> void fillLeaf(T parent, List<T> leafs) { List<T> children = parent.getChildren(); if (CollectionUtils.isEmpty(children)) { leafs.add(parent); return; } for (T child : children) { fillLeaf(child, leafs); } } }
|
实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| @Getter @Setter public class ExampleListVO implements TreeNode<Long> { private Long id; private Long pid; private Integer type; private String name; private String icon; private String code; private Integer status; private List<ResourceListVO> children;
@Override public Long id() { return this.id; }
@Override public Long parentId() { return this.pid; }
@Override public boolean root() { return Objects.equals(this.pid, 0L); }
@Override public void setChildren(List children) { this.children = children; } }
|
调用
1 2 3 4
| public List<ExampleListVO> getTreeList() { List<ExampleListVO> vos = this.exampleMapper.selectList(); return TreeUtils.generateTrees(vos); }
|