将Collection转换为Map< String,Collection< String>>使用Java 8流 [英] Convert a Collection to Map<String,Collection<String>> using java 8 streams

查看:144
本文介绍了将Collection转换为Map< String,Collection< String>>使用Java 8流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找使用java流将Collection<Placement>转换为Map<String, Collection<String>>的方法,其中Placement类如下

I am looking to convert a Collection<Placement> to Map<String, Collection<String>> using java streams, where the Placement class is as below

public class Placement {

   private String id;

   /* Links two placements, may be same for atleast 2 placements. */
   private String futureLinkId;
}

地图的键是将来的链接ID,值是展示位置ID.例如,如果有2个展示位置 p1 { id=1, futureLinkId=f1 }, p2 { id=2, futureLinkId=f1 },输出应为Map { f1 - { id1, id2 } }

The key for the map is future link id and the values are placement ids. For example if there are 2 placements p1 { id=1, futureLinkId=f1 }, p2 { id=2, futureLinkId=f1 } , the output should be Map { f1 - { id1, id2 } }

推荐答案

尽管其他人提供了复杂的解决方案,但这实际上很简单:

This is actually quite simple, despite the convoluted solutions others have offered:

Map<String, List<String>> map = placements.stream()
        .collect(groupingBy(Placement::getFutureLinkId, mapping(Placement::getId, toList())));

这篇关于将Collection转换为Map&lt; String,Collection&lt; String&gt;&gt;使用Java 8流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆