Why doesn't sorted(Comparator::reverseOrder) work?

故事扮演 提交于 2019-12-07 16:48:16

问题


The below Stream expression works perfectly fine:

Stream<String> s = Stream.of("yellow","blue", "white");
 s.sorted(Comparator.reverseOrder())
  .forEach(System.out::print);` //yellowwhiteblue

Why doesn't the equivalent one with method references compile?

s.sorted(Comparator::reverseOrder).forEach(System.out::print);

The type Comparator does not define reverseOrder(String, String) that is applicable here


回答1:


A method reference is telling Java "treat this method as the implementation of a single-method interface"--that is, the method reference should have the signature int foo(String,String) and thus implement Comparator<String>.

Comparator.reverseOrder() doesn't--it returns a Comparator instance. Since sorted is looking for a Comparator, it can take the result of the method call, but it can't use that method as the interface implementation.




回答2:


The line of code with method reference s.sorted(Comparator::reverseOrder) is telling Java that there is a static method with the signature of a trivial method comparator, it means with two parameters.

The class Comparator has only the static method reverseOrder without parameters, that's the reason of the compiling error.



来源:https://stackoverflow.com/questions/43036611/why-doesnt-sortedcomparatorreverseorder-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!