Java 8 Lambda,过滤HashMap,无法解析方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27841225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 8 Lambda, filter HashMap, cannot resolve method
提问by Daniel
I'm kinda new to Java 8's new features. I am learning how to filter a map by entries. I have looked at this tutorialand this postfor my problem, but I am unable to solve.
我对 Java 8 的新特性有点陌生。我正在学习如何按条目过滤地图。我已经查看了这个教程和这篇文章来解决我的问题,但我无法解决。
@Test
public void testSomething() throws Exception {
HashMap<String, Integer> map = new HashMap<>();
map.put("1", 1);
map.put("2", 2);
map = map.entrySet()
.parallelStream()
.filter(e -> e.getValue()>1)
.collect(Collectors.toMap(e->e.getKey(), e->e.getValue()));
}
However, my IDE (IntelliJ) says "Cannot resolve method 'getKey()'", thus unable to complile:
但是,我的 IDE (IntelliJ) 说“无法解析方法‘getKey()’”,因此无法编译:
Neither does this help:
Can anyone help me to solve this issue?
Thanks.
这也没有帮助:
谁能帮我解决这个问题?谢谢。
采纳答案by assylias
The message is misleading but your code does not compile for another reason: collect
returns a Map<String, Integer>
not a HashMap
.
该消息具有误导性,但您的代码由于另一个原因无法编译:collect
返回 a Map<String, Integer>
not a HashMap
。
If you use
如果你使用
Map<String, Integer> map = new HashMap<>();
it should work as expected (also make sure you have all the relevant imports).
它应该按预期工作(还要确保您拥有所有相关的导入)。
回答by sol4me
Your are returning Map not hashMap so you need to change map
type to java.util.Map
. Moreover you can use method referencerather then calling getKey, getValue. E.g.
您返回的是 Map 而不是 hashMap,因此您需要将map
type更改为java.util.Map
. 此外,您可以使用方法引用而不是调用 getKey、getValue。例如
Map<String, Integer> map = new HashMap<>();
map.put("1", 1);
map.put("2", 2);
map = map.entrySet()
.parallelStream()
.filter(e -> e.getValue() > 1)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
You could solve it by using some intellij help as well for e.g. if you press ctrl+alt+v
in front of
如果按你可以通过使用一些帮助的IntelliJ以及用于例如解决它ctrl+alt+v
前面
new HashMap<>();
map.put("1", 1);
map.put("2", 2);
map = map.entrySet()
.parallelStream()
.filter(e -> e.getValue() > 1)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
The variable created by intellij will be of exact type and you will get.
intellij 创建的变量将是精确类型,您将获得。
Map<String, Integer> collect = map.entrySet()
.parallelStream()
.filter(e -> e.getValue() > 1)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));