Answering a question, I came across this strange behavior of Java type inference. The following works without problems:
new HashMap<String,Integer>().entrySet().stream() .sorted(Map.Entry.comparingByValue());
but if we just add .reversed() to the end, it will fail unexpectedly:
new HashMap<String,Integer>().entrySet().stream() .sorted(Map.Entry.comparingByValue().reversed());
In detail: in the first case, the type comparingByValue() is displayed as Comparator<Map.Entry<String, Integer>> , but in the second case, it changes to Comparator<Map.Entry<Object, V>> .
The type reversed() is just a Comparator<T> - transformation of identity according to the type of its target. How does type inference lose it at such a seemingly trivial step? I canβt avoid a hunch that this should be due to an error in the output methods.
As another puzzle, if we just introduce a reversed() implementation that return Collections.reverseOrder(this); :
new HashMap<String,Integer>().entrySet().stream() .sorted(reverseOrder(Map.Entry.comparingByValue());
he is working again.
source share