java8 list 集合转化树形结构

79 阅读1分钟

1.定义节点类型实体类

import lombok.Data;

import java.util.List;

/**
 * @Author yang
 **/
@Data
public class Node {
    private String id;
    private String parentId;
    private String name;
    private List<Node> childList;
}

2.测试方法

import com.google.common.collect.Lists;
import com.google.gson.Gson;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * @Author yang
 **/
public class Test {

    public static void main(String[] args) {
        List<Node> nodes = init();
        List<Node> nodeList = nodes.stream()
                // 获取一级树形结构
                .filter(item -> item.getParentId().equals("1"))
                .peek(item -> {
                    // 赋值子列表
                    item.setChildList(getNodeChildList(item.getId(), nodes));
                }).collect(Collectors.toList());

        System.out.println(new Gson().toJson(nodeList));

    }

    public static List<Node> getNodeChildList(String parentId, List<Node> nodes) {
        return nodes.stream()
                .filter(item -> Objects.equals(item.getParentId(), parentId))
                .peek(item -> {
                    // 递归获取子列表
                    item.setChildList(getNodeChildList(item.getId(), nodes));
                }).collect(Collectors.toList());
    }
    
    public static List<Node> init(){
        //初始化数据
        Node entity = new Node();
        entity.setId("1006");
        entity.setName("测试一级目录");
        entity.setParentId("1");

        Node entity2 = new Node();
        entity2.setId("1007");
        entity2.setName("测试一级目录");
        entity2.setParentId("1");

        Node entity3 = new Node();
        entity3.setId("1008");
        entity3.setName("测试二级目录");
        entity3.setParentId("1006");
        return  Lists.newArrayList(entity,entity2,entity3);
    }
}

3.代码运行结果

[
    {
        "id":"1006",
        "parentId":"1",
        "name":"测试一级目录",
        "childList":[
            {
                "id":"1008",
                "parentId":"1006",
                "name":"测试二级目录",
                "childList":[]
            }
        ]
    },
    {
        "id":"1007",
        "parentId":"1",
        "name":"测试一级目录",
        "childList":[]
    }
]