Reverse a comparator in Java 8(在 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
这篇关于在 Java 8 中反转比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Java 8 中反转比较器
基础教程推荐
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
