在Java 8中反转比较器 [英] Reverse a comparator in 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:
返回由此流的元素组成的流,根据提供的<$ c $进行排序c>比较器。
此方法返回一个升序排序。我应该更改哪个参数,只是为了降序?
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 that imposes 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
这篇关于在Java 8中反转比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!