package com.zving.tree;
import java.util.ArrayList;
import java.util.List;
/**
树形结构实体类
@author clove
*/
public class Node {
private int id;
private int pid;
private String name;
private String type;
private List children = new ArrayList<>();
public Node(int id, int pid) {
this.id = id;
this.pid = pid;
//代码效果参考:http://www.zidongmutanji.com/zsjx/43551.html
public Node(int id, int pid, String name, String type) {
this(id, pid);
this.name = name;
this.type = type;
public int getId() {
return id;
public void setId(int id) {
public int getPid() {
return pid;
public void setPid(int pid) {
public String getName() {
return name;
public void setName(String name) {
public String getType() {
return type;
public void setType(String type) {
public List getChildren() {
return children;
public void setChildren(List children) {
this.children = children;
}
复制代码
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TreeController {
@RequestMapping("/tree")
public List getTree() {
List nodeList = getNodeList();
List tree = buildTree(nodeList);
return tree;
// 初始化数据集合
private List getNodeList() {
List list = new ArrayList();
Node node1 = new Node(1, 0, "公司库", "股票");
Node node2 = new Node(2, 0, "基金库", "基金");
Node node3 = new Node(111, 1, "A股市场", "股票");
Node node4 = new Node(112, 1, "港股市场", "股票");
Node node5 = new Node(211, 2, "公墓基金池", "基金");
Node node6 = new Node(212, 2, "非公墓基金池", "基金");
Node node7 = new Node(11111, 111, "基础池", "股票");
Node node8 = new Node(21211, 212, "可买池", "基金");
list.add(node1);
list.add(node2);
list.add(node3);
list.add(node4);
list.add(node5);
list.add(node6);
list.add(node7);
list.add(node8);
return list;
//代码效果参考:https://www.257342.com/sitemap/post.html
// 封装集合为树形结构
private List buildTree(List nodes) {
Map> children = nodes.stream().filter(node -> node.getPid() != 0)
.collect(Collectors.groupingBy(node -> node.getPid()));
nodes.forEach(node -> node.setChildren(children.get(node.getId())));
return nodes.stream().filter(node -> node.getPid() == 0).collect(Collectors.toList());