[英]How to create a map of maps from a list of maps with Java 8 streaming api
[英]Create a map from a list of maps
我有一张地图清单。
List<Map<Integer, String>>
例如,列表中的值
<1, String1>
<2, String2>
<1, String3>
<2, String4>
作为最终结果,我想要一个Map>,就像
<1, <String1, String3>>
<2, <String2, String4>>
我怎样才能在Java中实现这一点。
代码:
List<Map<Integer, String>> genericList = new ArrayList<Map<Integer,String>>();
for(TrackActivity activity : activityMajor){
Map<Integer, String> mapIdResponse = activity.getMapIdResponse();
genericList.add(mapIdResponse);
}
现在这个genericList是输入,从这个列表,基于我想要的相同ID
Map<Integer, List<String>> mapIdResponseList
基本上,要根据ID对String的响应进行分组,在列表中对具有相同id的响应进行分组,然后创建一个以id作为键并将列表作为其值的新映射。
您可以使用Java 8执行以下操作:
private void init() {
List<Map<Integer, String>> mapList = new ArrayList<>();
Map<Integer, String> map1 = new HashMap<>();
map1.put(1, "String1");
mapList.add(map1);
Map<Integer, String> map2 = new HashMap<>();
map2.put(2, "String2");
mapList.add(map2);
Map<Integer, String> map3 = new HashMap<>();
map3.put(1, "String3");
mapList.add(map3);
Map<Integer, String> map4 = new HashMap<>();
map4.put(2, "String4");
mapList.add(map4);
Map<Integer, List<String>> response = mapList.stream()
.flatMap(map -> map.entrySet().stream())
.collect(
Collectors.groupingBy(
Map.Entry::getKey,
Collectors.mapping(
Map.Entry::getValue,
Collectors.toList()
)
)
);
response.forEach((i, l) -> {
System.out.println("Integer: " + i + " / List: " + l);
});
}
这将打印:
整数:1 /列表:[String1,String3]
整数:2 /列表:[String2,String4]
解释(严重保证),我恐怕无法解释每一个细节,您需要先了解Java 8中引入的Stream
和Collectors
API的基础知识:
mapList
获取Stream<Map<Integer, String>>
。 flatMap
运算符,该运算符将流粗略地映射到已存在的流中。 Map<Integer, String>
转换为Stream<Map.Entry<Integer, String>>
并将它们添加到现有流中,因此它现在也是Stream<Map.Entry<Integer, String>>
。 Stream<Map.Entry<Integer, String>>
收集到Map<Integer, List<String>>
。 Collectors.groupingBy
,其产生的Map<K, List<V>>
基于分组功能,一个Function
是,映射Map.Entry<Integer, String>
到一个Integer
在这种情况下。 Map.Entry::getKey
,它在Map.Entry
并返回一个Integer
。 Map<Integer, List<Map.Entry<Integer, String>>>
如果我没有做任何额外的处理。 Collectors.groupingBy
添加一个下游,它必须提供一个收集器。 Map.Entry::getValue
将我的Map.Entry
条目映射到它们的String
值。 Collectors.toList()
,因为我想将它们添加到列表中。 Map<Integer, List,String>>
。 看看guavas MultiMap。 应该是你正在寻找的:
http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.