數據庫通常會提供樹形結構的數據的查詢函數,可是可能須要額外的配置,偶爾會由於設計上的失誤,會致使寫查詢語句跟吃屎同樣難受,數據量不大的狀況,索性全查在代碼中進行組合css
import java.util.*; /** * @author css * @data 2019/6/24 10:33 */ public class Test<T> { private List<Node<T>> list = new ArrayList<>(); public class Node<T> { Object id; Object pid; String name; T t; Node<T> parent; LinkedList<Node<T>> children = new LinkedList<>(); @Override public String toString() { return "Node{" + "id=" + id + ", pid=" + pid + ", name=" + name + ", t=" + t + ", children=" + children + '}'; } } public void add(Object id, Object pid, String name, T t) { Node<T> node = new Node<>(); node.id = id; node.pid = pid; node.name = name; node.t = t; list.add(node); } public Node<T> toTree(Object root) { for (Node<T> i : list) { for (Node<T> j : list) { if (i.id.equals(j.pid)) { i.children.add(j); j.parent = i; } } } for (Node<T> i : list) { if (root.equals(i.id)) { return i; } } return null; } public List<T> getParent(Node<T> node) { Node<T> p = node.parent; if (p == null) { return null; } else { List<T> list = new ArrayList<>(); while (p != null) { list.add(p.t); p = p.parent; } return list; } } public List<T> getChildren(Node<T> node) { LinkedList<Node<T>> c = new LinkedList<>(node.children); if (c.isEmpty()) { return null; } else { List<T> list = new ArrayList<>(c.size()); Node<T> e; while (!c.isEmpty()) { e = c.pollFirst(); list.add(e.t); if (!e.children.isEmpty()) { c.addAll(e.children); } } return list; } } public static void main(String[] args) { Test<String> t = new Test<>(); t.add(1, null, "1000", "node1"); t.add(2, 1, "1001", "node2"); t.add(3, 2, "1002", "node3"); t.add(4, 2, "1003", "node4"); Test.Node n = t.toTree(1); System.out.println(t.getChildren(n)); } }