Java 8 Lambda,过滤HashMap,无法解析方法

时间:2015-01-08 13:25:51

标签: java lambda

我不熟悉Java 8的新功能。我正在学习如何按条目过滤地图。我查看了this tutorialthis post来解决我的问题,但我无法解决。

@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()));
}

然而,我的IDE(IntelliJ)说&#34;无法解决方法&#39; getKey()&#39;&#34;因此无法修改: enter image description here

这也没有帮助: enter image description here
任何人都可以帮我解决这个问题吗? 谢谢。

2 个答案:

答案 0 :(得分:32)

该消息具有误导性,但由于其他原因,您的代码无法编译:{{1​​}}返回collect而不是Map<String, Integer>

如果您使用

HashMap

它应该按预期工作(同时确保您拥有所有相关的导入)。

答案 1 :(得分:4)

您将返回Map而不是hashMap,因此您需要将map类型更改为java.util.Map。此外,您可以使用方法引用,而不是调用getKey,getValue。 E.g。

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));

你可以通过使用一些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));

intellij创建的变量将是确切的类型,您将获得。

Map<String, Integer> collect = map.entrySet()
        .parallelStream()
        .filter(e -> e.getValue() > 1)
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));