收集地图流K,V.映射到K,List< V>. [英] Collect a Stream of Map<K,V> to Map<K,List<V>>
本文介绍了收集地图流K,V.映射到K,List< V>.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Stream< Map< K, V > >
,我试图将这些地图合并在一起,但是将重复的值保留在列表中,所以最终的类型将是Map< K, List<V> >
.有没有办法做到这一点?我知道toMap
收集器具有一个二进制函数,基本上可以选择返回哪个值,但是它可以跟踪转换后的列表吗?
I have a Stream< Map< K, V > >
and I'm trying to merge those maps together, but preserve duplicate values in a list, so the final type would be Map< K, List<V> >
. Is there a way to do this? I know the toMap
collector has a binary function to basically choose which value is returned, but can it keep track of the converted list?
即
如果a
是Stream< Map< String, Int > >
a.flatMap(map -> map.entrySet().stream()).collect(
Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (val1, val2) -> ??
);
推荐答案
Use groupingBy: see the javadoc, but in your case it should be something like that:
a.flatMap(map -> map.entrySet().stream())
.collect(
Collectors.groupingBy(
Map.Entry::getKey,
HashMap::new,
Collectors.mapping(Map.Entry::getValue, toList())
)
);
或者:
a.map(Map::entrySet).flatMap(Set::stream)
.collect(Collectors.groupingBy(
Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, toList())
)
);
这篇关于收集地图流K,V.映射到K,List< V>.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文