问题描述
我有一个 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
进行排序.
这个方法返回一个升序排序.我应该更改哪个参数,只是为了降序?
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
这篇关于反转 Java 8 中的比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!