Java 8 Lambda, filter HashMap, cannot resolve method

后端 未结 2 1068
忘了有多久
忘了有多久 2021-02-07 02:32

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.

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-07 02:46

    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 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 collect = map.entrySet()
            .parallelStream()
            .filter(e -> e.getValue() > 1)
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    

提交回复
热议问题