Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparator.comparing for Map.Entry in Java 8 [duplicate]

Given following code:

@Test
public void test7() {
    Map<String, Integer> sortedData = new HashMap<>();
    sortedData.put("One", 1);
    sortedData.put("Two", 2);
    sortedData.put("Three", 3);

    Stream<Map.Entry<String, Integer>> stream = sortedData.entrySet().stream();
    List<String> sorted = stream
            .sorted(Comparator.comparing(Map.Entry::getValue))
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());
} 

It succeeds to compile, but when I change

.sorted(Comparator.comparing(Map.Entry::getValue))

to

.sorted(Comparator.comparing(Map.Entry::getValue).reversed())

the compiler complains that Non static method can't be referenced in static context

I could imagine that it is because getValue is not a static method of Map.Entry, but I can't explain the problem here.

like image 220
Tom Avatar asked Sep 04 '26 09:09

Tom


1 Answers

It's interesting,

.sorted(Comparator.comparing(Map.Entry<String,Integer>::getValue).reversed ())

works.

Perhaps using raw Map.Entry confuses the compiler.

BTW, this also works:

.sorted(Collections.reverseOrder(Comparator.comparing(Map.Entry::getValue)))

(Collections.reverseOrder(this) is what reversed() returns)

like image 192
Eran Avatar answered Sep 06 '26 23:09

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!