在 Java 8 中反转比较器
我有一个 ArrayList 并希望按降序对其进行排序.我使用 java.util.stream.Stream.sorted(Comparator)
方法.下面是根据 Java API 的描述:
I have an ArrayList and want sort it in descending order. I use for it java.util.stream.Stream.sorted(Comparator)
method. Here is a description according Java API:
返回一个由该流的元素组成的流,根据提供的Comparator
排序.
Returns a stream consisting of the elements of this stream, sorted according to the provided
Comparator
.
这个方法返回一个升序排序.我应该更改哪个参数,只是为了降序?
this methods return me a sort with ascending order. Which parameter should I change, just to have the descending order?
推荐答案
你可以使用Comparator.reverseOrder()
有一个比较器,提供与自然顺序相反的顺序.
You can use Comparator.reverseOrder()
to have a comparator giving the reverse of the natural ordering.
如果要反转现有比较器的顺序,可以使用 Comparator.reversed()
.
If you want to reverse the ordering of an existing comparator, you can use Comparator.reversed()
.
示例代码:
Stream.of(1, 4, 2, 5)
.sorted(Comparator.reverseOrder());
// stream is now [5, 4, 2, 1]
Stream.of("foo", "test", "a")
.sorted(Comparator.comparingInt(String::length).reversed());
// stream is now [test, foo, a], sorted by descending length
相关文章