JAVA构建List集合为树形结构


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<Node> children = new ArrayList<>();

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

	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) {
		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 String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public List<Node> getChildren() {
		return children;
	}

	public void setChildren(List<Node> children) {
		this.children = children;
	}

}

 

package com.zving.tree;

import java.util.ArrayList;
import java.util.List;
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<Node> getTree() {
        List<Node> nodeList = getNodeList();
        List<Node> tree = buildTree(nodeList);
        return tree;
    }

    // 初始化数据集合
    private List<Node> getNodeList() {
        List<Node> list = new ArrayList<Node>();
        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;
    }

    // 封装集合为树形结构
    private List<Node> buildTree(List<Node> nodes) {
        Map<Integer, List<Node>> 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());
    }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM