天天看点

java实现简单的树形结构方法

1.首先定义实体类,包括本节点、父节点和叶子节点的实体列表:

@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;
    }
           

2.生产树形结构的方法:

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;
}

           

3.测试,先得到所有节点的数据列表,在通过公共方法得到树形结构:

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)));
}
           

结果如下:

[{
	"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
}]