天天看点

JAVA-简单树形结构

package com.qh.health.service;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.Data;

import java.util.List;
import java.util.Map;

/**
 * @author wzx
 * @since 2019-05-07
 */
@Data
public class NodeTest  {

    private Long id;

    private String name;

    private Long parentId;

    private List<NodeTest> children;

    public NodeTest(Long id, String name, Long parentId) {
        this.id = id;
        this.name = name;
        this.parentId = parentId;
    }

    public static void main(String[] args) {
        List<NodeTest> nodes = Lists.newArrayList();
        nodes.add(new NodeTest(1L, "一级", -1L));
        nodes.add(new NodeTest(2L, "一级-1", 1L));
        nodes.add(new NodeTest(3L, "一级-1-1", 2L));
        nodes.add(new NodeTest(4L, "二级", -1L));

        System.out.println(JSON.toJSONString(getTree(nodes)));
    }

    private static List<NodeTest> getTree(List<NodeTest> nodes) {
        Map<Long, NodeTest> nodeMap = Maps.newHashMap();
        List<NodeTest> rootList = Lists.newArrayList();
        for (NodeTest node : nodes) {
            nodeMap.put(node.getId(), node);
            Long parentId = node.getParentId();
            if (parentId == null || parentId <= 0) {
                rootList.add(node);
            }
        }
        for (NodeTest node : nodes) {
            Long parentId = node.getParentId();
            if (parentId == null || parentId <=0) {
                continue;
            }
            NodeTest pnode = nodeMap.get(parentId);
            if (pnode == null) {
                continue;
            }
            List<NodeTest> children = pnode.getChildren();
            if (children == null) {
                children = Lists.newArrayList();
                pnode.setChildren(children);
            }
            children.add(node);
        }
        return rootList;
    }

}

           

输出结果:

[{
	"children": [{
		"children": [{
			"id": 3,
			"name": "一级-1-1",
			"parentId": 2
		}],
		"id": 2,
		"name": "一级-1",
		"parentId": 1
	}],
	"id": 1,
	"name": "一级",
	"parentId": -1
}, {
	"id": 4,
	"name": "二级",
	"parentId": -1
}]