树状数据简易组装

今天有个需求,要组装一个树状数据,前端小伙伴让我后端直接把数据套成数返给他,分享一下:

        大概需求是这样的:

 

   开始组装写代码:

/**
 * 需要组装的树类
 */
@Data
public class Node {
    private Integer Id;
    private String name;
    private Integer pId;

    //子节点
    private List<Node> treeNode=new ArrayList<>();

    public Node(Integer id,  Integer pId,String name) {
        Id = id;
        this.name = name;
        this.pId = pId;
    }
}
实现类

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

public class assembleTree {
    public static void main(String[] args) {
        Node first=new Node(1,0,"first");
        Node second=new Node(2,1,"second");
        Node third=new Node(3,2,"third");
        Node fourth=new Node(4,1,"fourth");
        Node fifth=new Node(5,4,"fifth");
        List<Node> nodes = Arrays.asList(first, second, third, fourth, fifth);
        List<Node> treeNode = buildTrees(nodes);
        System.out.println(Arrays.deepToString(treeNode.toArray()));
    }


    private static List<Node> buildTrees(List<Node> nodes) {
        //先过滤非第一层的数据 然后组装成一个map并且进行分组 分组就是根据pid到他对应的子节点数据
         Map<Integer, List<Node>> nodesMap = nodes.stream().filter(node -> node.getPId() != 0)
                .collect(Collectors.groupingBy(node -> node.getPId()));
         
         //对nodes进行遍历循环 从map中拿到他对应节点的子节点 然后设置到treenode也就是子节点里面
        nodes.forEach(node -> node.setTreeNode(nodesMap.get(node.getId())));

        //过滤出pid=0的数据 也就是没有根节点的数据 直接返回 拼接完成
        List<Node> tree = nodes.stream().filter(node -> node.getPId() == 0).collect(Collectors.toList());
        return tree;

    }
}

我这里是打印出二维数组给大家看下比较抽象,用流写非常简单 核心思想大致就是这样,给大家看下控制台输出:

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值