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

Dan*_*iel 17 java lambda

我对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()));
}
Run Code Online (Sandbox Code Playgroud)

但是,我的IDE(IntelliJ)说"无法解析方法'getKey()'",因此无法编译: 在此输入图像描述

这也没有帮助: 在此输入图像描述
任何人都可以帮我解决这个问题吗?谢谢.

ass*_*ias 32

该消息具有误导性,但您的代码不会因其他原因而编译:collect返回a Map<String, Integer>而不是a HashMap.

如果你使用

Map<String, Integer> map = new HashMap<>();
Run Code Online (Sandbox Code Playgroud)

它应该按预期工作(也确保你有所有相关的进口).

  • 显然,编译器需要*一些时间来充分了解错误的真正原因.现在相当令人沮丧...... (2认同)

sol*_*4me 5

您返回的是 Map 而不是 hashMap,因此您需要将map类型更改为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));
Run Code Online (Sandbox Code Playgroud)

您也可以通过使用一些 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));
Run Code Online (Sandbox Code Playgroud)

intellij 创建的变量将具有精确的类型,您将得到。

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