【Java】集合流中toMap常用用法

有时候我们在数据库中经常会查询到如下的数据集合,我以资源数据为例。

[
{"type":1,"path":'https://www.xxx.com/x.jpg'},
{"type":2,"path":'https://www.xxx.com/y.jpg'}
]

此时我们想把这样的集合数据(你肯定能知道在这个集合中不同的type只有一条数据)根据资源类型type进行分组, 当然我再次强调,我要实现的是分组后,value不再是List的情况,如果想要变成List,用groupBy写法更合适。

以下是java测试代码

		//组装数据源
        List<ProductResources> resourcesList = new ArrayList<>();
        {
            //图片1
            ProductResources productResources = new ProductResources();
            productResources.setPath("https://www.xxx.com/x.jpg");
            productResources.setType(1);
            resourcesList.add(productResources);
        }
        {
            //视频1
            ProductResources productResources = new ProductResources();
            productResources.setPath("https://www.xxx.com/y.jpg");
            productResources.setType(2);
            resourcesList.add(productResources);
        }
		//进行拆分的核心方法
        if (CollectionUtils.isNotEmpty(resourcesList)) {
            //将type作为key,一个完整对象作为value
            Map<Integer, ProductResources> collect = resourcesList.stream().collect(Collectors.toMap(ProductResources::getType, o -> o));
            System.out.println("输出结果:"+JSONUtils.toString(collect));
        }

以上写法有一个前提条件,就是一再强调的,你肯定能知道在这个集合中不同的type只有一条数据。 所以如果type相同的不止一个,那上面的toMap就会有问题,会报错,以下是兼容写法。

Map<Integer, ProductResources> collect = resourcesList.stream().collect(Collectors.toMap(ProductResources::getType, o -> o,(n1,n2)->n1));

如果你还想根据type排个序,以下是最终写法。

Map<Integer, ProductResources> collect = resourcesList.stream().collect(Collectors.toMap(ProductResources::getType, o -> o,(n1,n2)->n1, TreeMap::new));
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杰肥啊

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值