将数据库的List转化为Tree

将数据库的List转化为Tree

参考

java—将数据库读取的list转tree

package com.mozq.common.date;

import lombok.Data;

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

@Data
public class DeptNode {
    private Integer id;
    private Integer parentId;
    private String name;
    private List<DeptNode> children;

    public static List<DeptNode> getTreeFor(List<DeptNode> list, Integer rootId){
        List<DeptNode> roots = new ArrayList<>();
        //children的值不设置为null
        list.forEach(e->e.setChildren(new ArrayList<>()));

        for (DeptNode deptNode : list) {
            if(deptNode.getParentId().equals(rootId)){
                roots.add(deptNode);
            }
            for (DeptNode node : list) {
                //寻找父子关系,为存在关系的建立关系
                if(deptNode.getParentId().equals(node.getId())){
                    if(Objects.isNull(node.getChildren())){
                        node.setChildren(new ArrayList<>());
                    }
                    node.getChildren().add(deptNode);
                }
            }
        }
        return roots;
    }
    public static List<DeptNode> getTree(List<DeptNode> list, Integer rootId){
        if(Objects.isNull(list) || list.isEmpty()){
            return new ArrayList<>();
        }
        //获取根列表
        List<DeptNode> roots = list.stream().filter(e -> e.getParentId().equals(rootId)).collect(Collectors.toList());
        if(roots.isEmpty()){
            //return null;
            return new ArrayList<>();
        }
        //为根设置子元素
        for (DeptNode root : roots) {
            List<DeptNode> children = getTree(list, root.getId());
            root.setChildren(children);
        }
        return roots;
    }

    public static void main(String[] args) {
        List<DeptNode> tree = DeptNode.getTree(data(), 0);
        System.out.println(tree);
        List<DeptNode> treeFor = DeptNode.getTreeFor(data(), 0);
        System.out.println(treeFor);
    }

    private static List<DeptNode> data(){
        DeptNode d1 = new DeptNode();
        d1.setName("haha");
        d1.setId(1);
        d1.setParentId(0);
        DeptNode d2 = new DeptNode();
        d2.setName("腾讯");
        d2.setId(2);
        d2.setParentId(0);

        DeptNode d11 = new DeptNode();
        d11.setName("研发");
        d11.setId(11);
        d11.setParentId(1);

        DeptNode d12 = new DeptNode();
        d12.setName("测试");
        d12.setId(12);
        d12.setParentId(1);

        List<DeptNode> deptNodeList = new ArrayList<>();
        deptNodeList.add(d1);
        deptNodeList.add(d2);
        deptNodeList.add(d11);
        deptNodeList.add(d12);
        return deptNodeList;
    }
}
posted @ 2020-02-16 12:21  没有理由不会呀  阅读(526)  评论(0编辑  收藏  举报