【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));

你可能感兴趣的:(Java,stream,java)