java中的列表转树

为了折腾出一个好用的列表转树的方法,我开始了漫长的探索。最终得到了我比较满意的方法。话不多说,直接上干货 首先定义一个节点类,用来接收一个统一的数据格式,定义类名为Node

package wang.aweb.pms.common.model.pojo;

import java.util.List;

public class Node {
    private Integer id;
    private Integer parentId;
    private String name;
    private List<Node> childList;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getParentId() {
        return parentId;
    }

    public void setParentId(Integer parentId) {
        this.parentId = parentId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Node> getChildList() {
        return childList;
    }

    public void setChildList(List<Node> childList) {
        this.childList = childList;
    }
}

第二部,定义一个工具类TreeUtils

package wang.aweb.pms.common.utils;

import wang.aweb.pms.common.model.pojo.Node;

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

public class TreeUtils {
    public static List<Node> listToTree(List<Node> nodes) {
        Map<Integer, List<Node>> nodeByPidMap = nodes.stream().collect(Collectors.groupingBy(Node::getParentId));
        // 循环一次设置当前节点的子节点
        nodes.forEach(node -> node.setChildList(nodeByPidMap.get(node.getId())));
        // 获取 一级列表
        return nodes.stream().filter(node -> Objects.equals(node.getParentId(), 0)).collect(Collectors.toList());
    }
}

第三步,调用

List<Department> departments=new ArrayList<>();
        departments=departmentMapper.selectList();
        List<Node> nodeList=new ArrayList<>();
        for (int i = 0; i < departments.size(); i++) {
            Department department =  departments.get(i);
            Node node=new Node();
            node.setId(department.getId());
            node.setParentId(department.getParentId());
            node.setName(department.getDepartmentName());
            nodeList.add(node);
        }
        List<Node> treeList= TreeUtils.listToTree(nodeList);
        return treeList;

至此结束,充分利用了stream处理。

评论

(= ̄ω ̄=)··· 暂无内容!

回复

您还未登录,请先登录或者注册