奇技淫巧_Java对象列表转树结构

本文介绍了如何使用Java中的对象引用将菜单列表转换为数组。通过Stream API进行数据处理,首先根据parentId对菜单列表进行分组,然后遍历列表并设置每个节点的子节点,最后过滤出顶层分类的数据。提供的代码示例清晰地展示了这一过程。
摘要由CSDN通过智能技术生成

介绍

本次利用Java中对象的引用来实现Java 对象列表转数组

代码

 		//将菜单列表根据parentId进行分组 key:parentId,value:List<Object>
        Map<Long, List<MenuListDto>> collect = list.stream().filter(node -> StringUtils.isNotBlank(node.getParentId().toString())).collect(Collectors.groupingBy(node -> node.getParentId()));
        //遍历菜单列表List,将Map中key=menu.getId()的值取出存入当前menu的children中
        list.forEach(node -> node.setChildren(collect.get(node.getId())));
        //list过滤掉非顶层分类的数据
        List<MenuListDto> treeMenu = list.stream().filter(node -> node.getParentId() == 0).collect(Collectors.toList());

简单代码解释

/**
 * @author huangqh
 * @create 2020/11/16 14:04
 * @Notes 注释
 */
@Data
@NoArgsConstructor
public class Node {
    private int id;

    private Node node;

    public Node(int id){
        this.id=id;
    }

    public static void main(String[] args) {
        Node A = new Node(1);
        Node B =new Node(2);
        Node C =new Node(3);
        A.setNode(B);
        B.setNode(C);
        //Node(id=1, node=Node(id=2, node=Node(id=3, node=null)))
        System.out.println(A);
        //Node(id=2, node=Node(id=3, node=null))
        System.out.println(B);
        //Node(id=3, node=null)
        System.out.println(C);
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值