comparator.reverseorder() 返回自然序的反向比较器,要求类型实现comparable接口;适用于integer、string等内置类型及自定义comparable类,常用于collections.sort、stream.sorted和treeset/treemap构造,推荐显式指定泛型如comparator.reverseorder()。

直接调用 Comparator.reverseOrder() 即可获得一个基于当前类型自然顺序的反向比较器,前提是该类型实现了 Comparable 接口(如 Integer、String、LocalDateTime 等)。
适用前提:类型必须支持自然排序
该方法只对实现了 Comparable 的类有效。例如:
-
Integer默认按数值升序 →reverseOrder()就是降序 -
String默认按字典序升序 → 反向即字典序降序 - 自定义类需实现
Comparable<yourclass></yourclass>才能使用
常见使用方式
多用于集合排序或流操作:
-
对 List 排序:
Collections.sort(list, Comparator.reverseOrder()); -
Stream 排序:
list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList()); -
TreeSet / TreeMap 构造:
new TreeSet(Comparator.reverseOrder());
注意泛型推断和显式指定
编译器通常能自动推断类型,但遇到泛型擦除或复杂场景时,建议显式指定:
- ✅ 推荐写法:
Comparator<integer>.reverseOrder()</integer> - ⚠️ 避免仅写
Comparator.reverseOrder()(无泛型,可能触发 unchecked 警告)
它不是“通用逆序”,而是“自然序的逆序”
reverseOrder() 不关心你之前用过什么比较逻辑,它只翻转 compareTo() 的结果。比如:
-
String::compareTo是字典序 →reverseOrder()就是字典逆序 - 若想按字符串长度逆序,不能靠它,得写
Comparator.comparing(String::length).reversed()











