[英]Stream sorted method with comparator
I don't understand why code1 works but code2 doesn't compile. 我不明白为什么code1工作但code2不编译。 Please explain. 请解释。
//Code1:
Stream<String> s = Stream.of("AA", "BB");
s.sorted(Comparator.reverseOrder())
.forEach(System.out::print);
//Code2:
Stream<String> s = Stream.of("AA", "BB");
s.sorted(Comparator::reverseOrder)
.forEach(System.out::print);
The difference between the two is code1 uses Comparator.reverseOrder()
while code2 uses Comparator::reverseOrder
两者之间的区别是code1使用Comparator.reverseOrder()
而code2使用Comparator::reverseOrder
Because the first example is a factory-method
so when you inspect it, you see that you get a comparator back. 因为第一个例子是factory-method
所以当你检查它时,你会看到你得到一个比较器。
But the second one is a method-reference
which you could write like this: 但第二个是method-reference
,你可以像这样写:
Stream<String> s = Stream.of("AA", "BB");
s.sorted(() -> Comparator.reverseOrder()) // no semantic difference!
.forEach(System.out::print);
But it has a whole different meaning because this time you are given Stream#sorted()
a Supplier<Comparator<?>>
but it just needs a Comparator<?>
但它有完全不同的含义,因为这次你给Stream#sorted()
一个Supplier<Comparator<?>>
但它只需要一个Comparator<?>
Small Sidenote: Don't store streams in variables, use them directly. 小旁注:不要将流存储在变量中,直接使用它们。 So i would suggest you just write: 所以我建议你写一下:
Stream.of("AA", "BB")
.sorted(Comparator.reverseOrder())
.forEach(System.out::print);
The error message from the compiler should tell you that. 来自编译器的错误消息应该告诉您。
sorted()
expects a Comparator instance. sorted()
需要一个Comparator实例。 Comparator.reverseOrder()
returns a Comparator instance. Comparator.reverseOrder()
返回Comparator实例。 So that works fine. 所以这很好。
Comparator::reverseOrder
is a method reference to the reverseOrder() method of Comparator. Comparator::reverseOrder
是Comparator::reverseOrder
的reverseOrder()方法的方法引用。 So your code basically says: each time you need to compare two strings, pass them as argument to Comparator.reverseOrder
to compare them. 所以你的代码基本上说:每次你需要比较两个字符串时,将它们作为参数传递给Comparator.reverseOrder
来比较它们。 But that can't possibly work. 但那不可能奏效。 This method takes nothing as argument, and returns a Comparator. 此方法不作为参数,并返回Comparator。 So it doesn't match the signature of a Comparator<String>
, which is supposed to take two Strings as argument, and return an integer. 因此它与Comparator<String>
的签名不匹配,后者应该将两个Strings作为参数,并返回一个整数。
If you had a method such as 如果你有一个方法,如
class Foo
public static int compareStrings(String s1, String s2) {
...
}
}
Then you could use 然后你可以使用
sorted((s1, s2) -> Foo.compareStrings(s1, s2))
which you can transform, using a method reference, to 您可以使用方法引用转换为
sorted(Foo::compareStrings)
Because compareStrings, just like the unique abstract method of Comparator<String>
, takes two Strings as argument and returns an int. 因为compareStrings,就像Comparator<String>
的唯一抽象方法一样,将两个字符串作为参数并返回一个int。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.