简体   繁体   English

为什么 sorted(Comparator::reverseOrder) 不起作用?

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

The below Stream expression works perfectly fine:下面的 Stream 表达式工作得很好:

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 Comparator 类型没有定义这里适用的 reverseOrder(String, String)

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> .方法引用告诉 Java“将此方法视为单方法接口的实现”——也就是说,方法引用应该具有签名int foo(String,String)并因此实现Comparator<String>

Comparator.reverseOrder() doesn't--it returns a Comparator instance . Comparator.reverseOrder()不会——它返回一个Comparator实例 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.由于sorted正在寻找一个Comparator ,它可以采取的方法调用的结果,但它不能使用该方法的接口实现。

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.带有方法引用s.sorted(Comparator::reverseOrder) 的那行代码告诉 Java 有一个带有普通方法比较器签名的静态方法,这意味着有两个参数。

The class Comparator has only the static method reverseOrder without parameters, that's the reason of the compiling error. Comparator类只有静态方法reverseOrder没有参数,这就是编译错误的原因。

Stream<String> s=Stream.of("yellow","blue", "white");
        s.sorted(String::compareTo)
                .forEach(System.out::println);

if you still want to use a method reference then the above will work.如果您仍然想使用方法引用,那么上述方法将起作用。 This seems to be a common question in OCP Java 8 certification.这似乎是 OCP Java 8 认证中的常见问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM