在流的排序方法中使用 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<T>
, 正确的? Comparator<T>
是一个功能接口(interface)。它表示一个函数,该函数接受 2 个参数并返回一个 int
。指示哪个参数更大或它们是否相等。
在Comparator.reverseOrder()
的情况下, reverseOrder
是一种返回 Comparator<T>
的方法.在这种情况下,您调用该方法,它返回一个 Comparator
。可以用作 sorted
的参数.一切都很好。
在Comparator::reverseOrder
的情况下, 你没有调用 reverseOrder
.相反,您正在传递 reverseOrder
作为 sorted
的函数.如上所述,sorted
将接受一个带有 2 个参数并返回 int
的函数, 但你给了它 reverseOrder
, 它不带参数并返回一个 Comparator<T>
.看到这里的不匹配了吗?
Expected: a function that takes 2 parameters and returns an int OR a
Comparator<T>
objectWhat you gave it: a function that takes no parameters and returns a
Comparator<T>
这会导致编译器错误。
关于java - 在流的排序方法中使用 Comparator::reverseOrder 和 Comparator.reverseOrder() 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49915853/