Comparator.reversed() type inference issue
Attila Szegedi
szegedia at gmail.com
Sun Jun 7 12:32:35 UTC 2020
Hi folks,
I'm teaching Java lately, and while teaching streams I use that good old chestnut, the word count example. I'm baffled with some type inference woes, though… trying to specify a reverse comparator using Comparator.reversed() makes javac sad, e.g. this does not compile[1]:
Map<String, Long> x = someMap();
var rs1 = x.entrySet().stream().sorted(
Map.Entry.comparingByValue().reversed()
);
On the other hand, using Collections.reverseOrder does compile:
var rs2 = x.entrySet().stream().sorted(
Collections.reverseOrder(
Map.Entry.comparingByValue()
)
);
Happens on both Java 11 and 14. It’s just baffling because based on type signatures, it seems reasonable the first form should work as well.
Thanks for any enlightenment!
Attila.
---
[1] -Xdiags:verbose on Java 14 says:
error: no suitable method found for sorted(Comparator<Entry<Object,V#1>>)
var rs1 = x.entrySet().stream().sorted(
method Stream.sorted() is not applicable
(actual and formal argument lists differ in length)
method Stream.sorted(Comparator<? super Entry<String,Long>>) is not applicable
(argument mismatch; Comparator<Entry<Object,V#2>> cannot be converted to Comparator<? super Entry<String,Long>>)
where V#1,V#2 are type-variables:
V#1 extends Comparable<? super V#1>
V#2 extends Comparable<? super V#2>
More information about the core-libs-dev
mailing list