-1

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?

Alpharius
  • 489
  • 5
  • 12
  • Does this answer your question? [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – QBrute Oct 02 '21 at 21:11

2 Answers2

1

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.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

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