JAVA 快速构建树形结构

  • JDK 1.8+
  • Node 中pid 为 0 的是根节点
public class Node {
    private int id;
    private int pid;
    private String name;
    private List<Node> sub = new ArrayList<>();
    public Node(int id, int pid) {
        this.id = id;
        this.pid = pid;
    }

    public Node(int id, int pid, String name) {
        this(id, pid);
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getPid() {
        return pid;
    }

    public void setPid(int pid) {
        this.pid = pid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Node> getSub() {
        return sub;
    }

    public void setSub(List<Node> sub) {
        this.sub = sub;
    }
}
public class TreeUtil {
    public static List<Node> buildTree(List<Node> nodes) {
        Map<Integer, List<Node>> sub = nodes.stream().filter(node -> node.getPid() != 0).collect(Collectors.groupingBy(node -> node.getPid()));
        nodes.forEach(node -> node.setSub(sub.get(node.getId())));
        return nodes.stream().filter(node -> node.getPid() == 0).collect(Collectors.toList());
    }
}
public class Main {
    public static void main(String[] args) {
        Node dennis = new Node(1, 0, "dennis");
        Node calm = new Node(2, 0, "calm");
        Node daughter = new Node(3, 1, "daughter");
        Node grandson = new Node(4, 3, "grandson");
        Node son = new Node(5, 2, "son");
        List<Node> nodes = Lists.newArrayList(dennis, calm, daughter, son, grandson);
        List<Node> tree = TreeUtil.buildTree(nodes);
        System.out.println(JSON.toJSONString(tree));
    }
}
[
  {
    "id": 1,
    "name": "dennis",
    "pid": 0,
    "sub": [
      {
        "id": 3,
        "name": "daughter",
        "pid": 1,
        "sub": [
          {
            "id": 4,
            "name": "grandson",
            "pid": 3
          }
        ]
      }
    ]
  },
  {
    "id": 2,
    "name": "calm",
    "pid": 0,
    "sub": [
      {
        "id": 5,
        "name": "son",
        "pid": 2
      }
    ]
  }
]

 

posted @ 2020-02-29 15:49  黄进广寒  阅读(3679)  评论(1编辑  收藏  举报