You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Stream的sorted方法中使用Comparator::reverseOrder与Comparator.reverseOrder()的区别

Difference Between Comparator::reverseOrder and Comparator.reverseOrder() in Stream.sorted()

Let’s break down the key difference here, starting with what the sorted method actually expects. The Stream.sorted(Comparator<T>) method requires a ready-to-use Comparator<T> instance to sort stream elements—so the distinction boils down to whether you’re passing that instance directly, or a reference to how to create it.

1. Why Comparator.reverseOrder() works

Comparator.reverseOrder() is a static method that immediately returns a Comparator<T> instance (one that reverses the natural ordering of elements). When you call it with parentheses, you’re executing the method right away and passing the finished Comparator object to sorted. This perfectly matches the method’s parameter type, which is why your first code snippet compiles and runs without issues:

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()) // Returns a ready Comparator<String>
          .findFirst().ifPresent(System.out::println);

2. Why Comparator::reverseOrder fails to compile

Comparator::reverseOrder is a method reference to the static reverseOrder() method. Instead of passing the Comparator instance itself, this reference points to the method that creates the Comparator. In functional interface terms, this acts like a Supplier<Comparator<T>>—a function that takes no arguments and returns a Comparator.

The problem? Stream.sorted() doesn’t accept a Supplier—it needs the actual Comparator instance, not a way to generate one. The compiler throws an error because there’s a type mismatch: you’re trying to pass a "factory for comparators" where a "finished comparator" is required.

When would you use Comparator::reverseOrder?

You’d use this method reference if you were working with a method that expects a Supplier<Comparator<T>>. For example:

// A method that accepts a supplier of comparators
void sortWithSupplier(Supplier<Comparator<String>> comparatorSupplier) {
    Stream<String> stream = Stream.of("a", "b", "c");
    stream.sorted(comparatorSupplier.get()).forEach(System.out::println);
}

// Here, the method reference works perfectly:
sortWithSupplier(Comparator::reverseOrder);

But since Stream.sorted() doesn’t take a Supplier, this reference isn’t suitable for your original use case.


内容的提问来源于stack exchange,提问作者Oro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:55:01