在Java 8中使用Lambda将流收集到HashMap中 [英] Collect stream into a HashMap with Lambda in Java 8
问题描述
我有一个HashMap,需要使用某些函数进行过滤:
I have a HashMap which I need to filter using some function:
HashMap<Set<Integer>, Double> container
Map.Entry<Set<Integer>, Double> map = container.entrySet()
.stream()
.filter(k -> k.getKey().size() == size)
对于size = 2,以下内容应有效:
For the size = 2 the following should be valid:
containerBeforeFilter = {1,2,3} -> 1.5, {1,2} -> 1.3
containerAfterFilter = {1,2} -> 1.3
在过滤器中应用了函数之后,我想再次将结果收集到HashMap中.但是,当我尝试应用建议的方法在这里,我收到非法声明.
After I applied the function in the filter, I want to collect results again into a HashMap. However, when I try to apply the method suggested here, I'm getting illegal statements.
因此,在过滤器之后应用的以下语句是非法的:
So the following statement, applied after the filter, is illegal:
.collect(Collectors.toMap((entry) -> entry.getKey(), (entry) -> entry.getValue()));
在唯一的标准是满足某些键的情况下,收集不变的地图值的正确方法是什么?
What would be the proper way of collecting unchanged map values, where the only criteria is satisfying some key?
更新
上面代码中的错误是变量 map
的声明类型.应该是 Map
,而不是 Map.Entry
.
The mistake in the above code is the declared type of the variable map
. It should have been Map
rather than Map.Entry
.
所以现在的功能代码是:
So the now functional code is:
Map<Set<Integer>, Double> map = container.entrySet()
.stream()
.filter(k -> k.getKey().size() == size)
.collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue()));
推荐答案
在您的示例中, Collectors.toMap
似乎没有接受 stream.collect
的类型参数.并且仅返回 Map< Object,Object>
.
Seems that Collectors.toMap
does not pick up the type arguments of stream.collect
in your example and only returns a Map<Object,Object>
.
作为一种解决方法,您可以自己创建结果图,然后在最后一步中将过滤后的条目添加到结果图:
As a workaround you can create the result map yourself and in the last stream step add the filtered entries to the result map:
Map<Set<Integer>, Double> result = new HashMap<>();
container.entrySet()
.stream()
.filter(entry -> entry.getKey().size() == size)
.forEach(entry -> result.put(entry.getKey(), entry.getValue()));
这篇关于在Java 8中使用Lambda将流收集到HashMap中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!