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

2022-09-02 01:02:37

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

但是,我的IDE(IntelliJ)说“无法解析方法'getKey()'”,因此无法编译:enter image description here

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


答案 1

该消息具有误导性,但您的代码由于其他原因而无法编译:返回一个不是 .collectMap<String, Integer>HashMap

如果您使用

Map<String, Integer> map = new HashMap<>();

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


答案 2

您返回的是 Map 而不是 hashMap,因此您需要将类型更改为 。此外,您可以使用方法引用,而不是调用getKey,getValue。例如:mapjava.util.Map

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

推荐