Java Streams:获取按内部映射键分组的值 [英] Java Streams: get values grouped by inner map key
问题描述
我有地图< A,地图< B,C>>
我希望得到地图< B,列表< C>> ;
来自它使用Java Streams。
I have Map<A, Map<B, C>>
and I want to get Map<B, List<C>>
from it using Java Streams.
我尝试按如下方式进行:
I try to do it as follows:
public <A, B, C> Map<B, List<C>> groupsByInnerKey(Map<A, Map<B, C>> input) {
return input.values()
.stream()
.flatMap(it -> it.entrySet().stream())
.collect(Collectors.groupingBy(Map.Entry::getKey));
}
我的期望:
-
flatMap
提供流
Map.Entry< ; B,C>
-
collect(Collectors.groupingBy(...))
获取的功能适用于Map.Entry< B,C>
并返回B
,因此它会收集<$ c $的值c> C 进入列表< C>
。
flatMap
gives aStream
ofMap.Entry<B, C>
collect(Collectors.groupingBy(...))
takes function which is applied toMap.Entry<B, C>
and returnsB
, thus it collects values ofC
intoList<C>
.
但它不能编译,字面意思:
But it doesn't compile, literally:
无法从静态上下文引用非静态方法
Non-static method cannot be referenced from a static context
在最后一行 Map.Entry :: getKey
。
有人可以解释什么是错的或者什么是实现我想要的正确方法?
Can someone explain what is wrong or what is the right way to achieve what I want?
推荐答案
您的Stream由 Map.Entry
对象组成,但是您希望收集的实际上是条目的值,而不是条目本身。使用当前代码,您将获得 Map< B,List< Map.Entry< B,C>>>
。
Your Stream is composed of Map.Entry
objects but want you want to collect is actually the value of the entry, not the entry itself. With your current code, you would be obtaining a Map<B, List<Map.Entry<B, C>>>
.
因此,您只是错过了对 Collectors.mapping
。此收集器将使用给定的映射器函数映射Stream元素,并将该结果收集到下游容器中。在这种情况下,映射器是 Map.Entry :: getValue
(因此返回映射条目中的值),下游收集器收集到列表中
。
As such, you are just missing a call to Collectors.mapping
. This collector will map the Stream element with the given mapper function and collect that result into the downstream container. In this case, the mapper is Map.Entry::getValue
(so returning the value from the map entry) and the downstream collector collects into a List
.
public <A, B, C> Map<B, List<C>> groupsByInnerKey(Map<A, Map<B, C>> input) {
return input.values()
.stream()
.flatMap(it -> it.entrySet().stream())
.collect(Collectors.groupingBy(
Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())
));
}
这篇关于Java Streams:获取按内部映射键分组的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!