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

编程知识 行业动态 更新时间:2024-06-13 00:22:04

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

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

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

以下是java测试代码

		//组装数据源
        List<ProductResources> resourcesList = new ArrayList<>();
        {
            //图片1
            ProductResources productResources = new ProductResources();
            productResources.setPath("https://www.xxx/x.jpg");
            productResources.setType(1);
            resourcesList.add(productResources);
        }
        {
            //视频1
            ProductResources productResources = new ProductResources();
            productResources.setPath("https://www.xxx/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));

更多推荐

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

本文发布于:2023-04-01 16:34:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/4faeb5d4c3c67fe543e1d511fa65f953.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:常用   Java   toMap

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!