Java 8 Lambda, filter HashMap, cannot resolve meth

2020-06-01 07:04发布

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 tutorial and this post for my problem, but I am unable to solve.

@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: enter image description here

Neither does this help: enter image description here
Can anyone help me to solve this issue? Thanks.

标签: java lambda
2条回答
Viruses.
2楼-- · 2020-06-01 07:29

The message is misleading but your code does not compile for another reason: collect returns 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).

查看更多
做个烂人
3楼-- · 2020-06-01 07:36

Your are returning Map not hashMap so you need to change map type to java.util.Map. Moreover you can use method reference rather then calling 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));

You could solve it by using some intellij help as well for e.g. if you press ctrl+alt+v in front of

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.

Map<String, Integer> collect = map.entrySet()
        .parallelStream()
        .filter(e -> e.getValue() > 1)
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
查看更多
登录 后发表回答