本文介绍了在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:
此方法返回一个升序排序。我应该更改哪个参数,只是为了降序?
this methods return me a sort with ascending order. Which parameter should I change, just to have the descending order?
推荐答案
您可以使用有一个比较器强制反转自然排序。
You can use Comparator.reverseOrder()
to have a comparator that imposes the reverse of the natural ordering.
如果要反转现有比较器的顺序,可以使用。
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中反转比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!