【发布时间】:2018-04-19 08:05:55
【问题描述】:
Comparator::reverseOrder 和Comparator.reverseOrder() 在流的排序方法中使用时有什么区别。
Stream<String> streamText = Stream.of("over the river", "through the woods", "to grandmother's house we go");
这行得通:
streamText.filter(n -> n.startsWith("t"))
.sorted(Comparator.reverseOrder())
.findFirst().ifPresent(System.out::println);
但这不能编译:
streamText.filter(n -> n.startsWith("t"))
.sorted(Comparator::reverseOrder)
.findFirst().ifPresent(System.out::println);
【问题讨论】:
-
sorted接受Comparator作为其参数。Comparator::reverseOrder不是比较器。它是一种返回比较器的方法。所以你需要调用它并将返回值传递给sorted。 -
一个是方法调用,另一个是方法引用。它们不可互换。如果您能解释为什么您认为
sorted(Comparator::reverseOrder)应该能够编译,这将有所帮助。
标签: java sorting java-8 java-stream comparator