Why do you think this works
but this doesn’t
? For some reason it starts to underline the very same parameter of
comparing() and says, “Non-static method cannot be referenced from a static context”. If I add one more element
.sorted(Comparator.comparing(Map.Entry::getValue).reversed().thenComparing(e -> e.getKey()))
the IDE forgets that it’s a stream of
Map.Entries altogether and complains that it “cannot resolve method
The reason why the second line of code doesn’t work is that the
Comparator.comparing() method returns a
Comparator that compares the specified key extracted from a given object. The
getValue() method is a non-static method of the
Map.Entry interface, which means it can only be called on an instance of a
Map.Entry object. When you try to reference this method from a static context, such as in a
Comparator lambda expression, you will get the error “Non-static method cannot be referenced from a static context”.
To fix this, you can use a method reference instead of a lambda expression to reference the
getValue() method of the
Map.Entry object. This way, the method reference will be evaluated on the instance of the
Map.Entry object passed to the
Comparator at runtime.
The third line of code you provided doesn’t work because once you call the
reversed() method on the
Comparator, it returns a
Comparator that reverses the natural order of the objects being compared. Since the objects being compared in this case are
Map.Entry objects, which don’t have a natural order, the
reversed() method doesn’t make sense.
To fix this, you can add a
Comparator to the
thenComparing() method that compares the
Map.Entry objects by their keys, like so:
This will first sort the
Map.Entry objects by their values in descending order, and then sort them by their keys in ascending order if their values are equal.
I don’t understand. I already use method reference in the second code snippet
This post was flagged by the community and is temporarily hidden.
But your code line is identical to my second piece of code
Because getValue() and getKey() are non-static methods in the Map, the error “Non-static method cannot be accessed from a static context” occurs. The Comparator and the entry interface. The comparing() function is static. This implies you’ll need a Map instance. getValue() or getKey() entry ().
To resolve the issue, use a lambda expression to retrieve the value or key from the Map.
Object of entry:
.sorted(Comparator.comparing(e -> e.getValue()).reversed())
.sorted(Comparator.comparing(e -> e.getValue()).reversed().thenComparing(e -> e.getKey()))
This method, you’re building a Comparator object with a lambda expression that pulls the value or key from the Map. Instead of attempting to invoke non-static methods directly on the Map, use the Entry object. The object of entry.