Home > database >  Why Map.entry::getKey and Map.entry::getValue doesn't work when sorting hashmap in a stream?
Why Map.entry::getKey and Map.entry::getValue doesn't work when sorting hashmap in a stream?

Time:10-03

I'm trying to sort a HashMap using a stream :

public class sortByValue implements Sorting{
    @Override
    public LinkedHashMap<String,Integer> sort(Map map) {
        return map.entrySet().stream().
                              sorted(Map.Entry.comparingByValue()).
                              collect(Collectors.toMap(
                                        Map.Entry::getKey,
                                        Map.Entry::getValue,
                                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));
    }
}

But it gives me an error :

Non-static method cannot be referenced from a static context it is on the functions Map.Entry::getKey,Map.Entry::getValue But I saw the same example on the website.Maybe someone understands what the mistake is?

CodePudding user response:

Replace method's parameter from Map map to Map<String, Integer> map and it will work correctly. Currently your map generic types are mismatching.

Or if you want to make it more generic, then you can do it like this: public <S, T extends Comparable<T>>LinkedHashMap<S, T> sort(Map<S, T> map) {

CodePudding user response:

To fix the error, change the parameter from a raw Map

Map map

to a typed Map:

Map<String, Integer> map

Giving:

public Map<String, Integer> sort(Map<String, Integer> map) {
return map.entrySet().stream().
        sorted(Map.Entry.comparingByValue()).
        collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (oldValue, newValue) -> oldValue, LinkedHashMap::new));
}

Or to make it work with any map type:

public <K, V extends Comparable<V>> Map<K, V> sort(Map<K, V> map) {

Note that the return type doesn’t need to be LinkedHashMap. As per Liskov Substitution Principle you should always use the abstract type where possible.

I haven't looked deeply into it, but I suspect you have encountered an unintentional match with a synthetic method.

Generics has some weird aspects when you use raw types, which are to be avoided.

  • Related