You can use Comparator.reverseOrder() to have a comparator giving the reverse of the natural ordering.

If you want to reverse the ordering of an existing comparator, you can use Comparator.reversed().

Sample code:

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
Answer from Tunaki on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Comparator.html
Comparator (Java Platform SE 8 )
October 20, 2025 - Returns a comparator that imposes the reverse of the natural ordering.
🌐
GeeksforGeeks
geeksforgeeks.org › java › comparator-reverseorder-method-in-java-with-examples
Comparator reverseOrder() method in Java with examples - GeeksforGeeks
July 11, 2025 - The reverseOrder() method of Comparator Interface in Java returns a comparator that use to compare Comparable objects in reverse of natural order.
🌐
Baeldung
baeldung.com › home › java › guide to java comparator.comparing()
Guide to Java Comparator.comparing() | Baeldung
January 8, 2024 - When invoked on an existing Comparator, the instance method Comparator.reversed returns a new Comparator that reverses the sort order of the original.
🌐
Apache Commons
commons.apache.org › proper › commons-collections › apidocs › org › apache › commons › collections4 › comparators › ReverseComparator.html
ReverseComparator (Apache Commons Collections 4.5.0 API)
Creates a comparator that compares objects based on the inverse of their natural ordering. Using this Constructor will create a ReverseComparator that is functionally identical to the Comparator returned by java.util.Collections.reverseOrder(). See Also: Collections.reverseOrder() public ...
🌐
Coderanch
coderanch.com › t › 738448 › java › Comparator-comparing-reversed
Comparator - comparing() & reversed() (Beginning Java forum at Coderanch)
Comparator comparator = Comparator.comparing( (Test) x -> x.getNum() ).reversed();. Compile error output when I call chained Comparator reversed() on line #21.
🌐
Medium
medium.com › @AlexanderObregon › javas-comparator-reverseorder-method-explained-9f9b8bebd87b
Java’s Comparator.reverseOrder() Method Explained | Medium
January 26, 2025 - The Comparator.reverseOrder() method in the java.util.Comparator class is a simple and effective tool for creating a comparator that sorts input in reverse (descending) order. It's helpful for sorting collections in descending order, whether ...
🌐
Javaprogramto
javaprogramto.com › 2021 › 12 › java-8-comparator-comparing-reverse.html
Java 8 Comparator Comparing Reverse Order JavaProgramTo.com
Look at the simple examples of how to create the comparator with Lambda? In this section, we will learn how to use reverse() method on custom objects to reverse the existing sorting logic. This will help to reduce the rewriting of the same code. ... package com.javaprogramto.java8.comparator.reverse; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; public class ComparatorReverse5 { public static void main(String[] args) { List<Teacher> teachers = new ArrayList<>(); teachers.add(new Teacher("Rajesh", "Science", 10)); teachers.ad
Find elsewhere
🌐
Tabnine
tabnine.com › home page › code › java › java.util.comparator
java.util.Comparator.reversed java code examples | Tabnine
private List<URIStatus> sortByFieldAndOrder( List<URIStatus> statuses, String sortField, boolean reverse) throws IOException { Optional<Comparator<URIStatus>> sortToUse = Optional.ofNullable( SORT_FIELD_COMPARATORS.get(sortField)); if (!sortToUse.isPresent()) { throw new InvalidArgumentException(ExceptionMessage.INVALID_ARGS_SORT_FIELD .getMessage(sortField)); } Comparator<URIStatus> sortBy = sortToUse.get(); if (reverse) { sortBy = sortBy.reversed(); } return statuses.stream().sorted(sortBy).collect(Collectors.toList()); }
🌐
ConcretePage
concretepage.com › java › java-8 › java-comparator-reversed
Java Comparator.reversed
reversed() is the default method of Java Comparator functional interface. This method is introduced in Java 8. reversed returns a Comparator that imposes the reverse ordering of this Comparator.
🌐
GeeksforGeeks
geeksforgeeks.org › java › comparator-reversed-method-in-java-with-examples
Comparator reversed() method in Java with examples - GeeksforGeeks
July 11, 2025 - Return value: This method returns a comparator that imposes the reverse ordering of this comparator. ... // Java program to demonstrate // Comparator.reversed() method import java.util.*; public class GFG { public static void main(String[] args) { String[] Arraystrings = { "aman", "amar", "avik" }; System.out.println("before sort : " + Arrays.toString(Arraystrings)); Comparator<String> comp = (String::compareTo); Arrays.sort(Arraystrings, comp.reversed()); System.out.println("after sort : " + Arrays.toString(Arraystrings)); } }
🌐
Stack Exchange
softwareengineering.stackexchange.com › questions › 197242 › best-practice-to-sort-then-reverse-or-write-backwards-comparator
language agnostic - Best practice to sort then reverse, or write "backwards" comparator? - Software Engineering Stack Exchange
If you already have written a comparator, it's of course best to modify it so that the standard sort (into "ascending" order) does what you want. The second best thing is to use whatever switches or tricks are available in your language's standard sorting methods. Such as this in Java: ... The third option, reversing an already sorted list, isn't a categorically bad solution.
🌐
O'Reilly
oreilly.com › library › view › jakarta-commons-cookbook › 059600706X › ch04s04.html
4.3. Reversing a Comparator - Jakarta Commons Cookbook [Book]
Use ReverseComparator to reverse the effects of a Comparator. Supply an existing Comparator to the constructor of ReverseComparator, and it reverses the effects of that Comparator.
🌐
TutorialsPoint
tutorialspoint.com › get-reverse-order-using-comparator-in-java
Get reverse order using Comparator in Java
Comparator comparator = ... are: "); for (int i = 0; i < n; i++) { System.out.println(str[i]); } The string array is sorted in reverse order using the java.util.Arrays.sort() method....
Top answer
1 of 3
23

It's easier to understand what's going on if you put each call on a line:

Comparator.comparingInt(Amount::getLineNum)
    .thenComparingInt(Amount::getStartIndex)
    .reversed()
    .thenComparingDouble(Amount::getValue)

That reversed() returns a comparator which reverses the results of the comparator it's called on... which is "the comparator which first compares the line number, then the start index." It's not like it's "bracketed" to just the scope of the previous thenComparingInt() call, which is how your previous formatting made it look like.

You could do it as:

Comparator.comparingInt(Amount::getLineNum)
    .thenComparing(Comparator.comparingInt(Amount::getStartIndex).reversed())
    .thenComparingDouble(Amount::getValue)

At that point it's only the start index comparison that's reversed.

2 of 3
2

From The docs:

reversed(): Returns a comparator that imposes the reverse ordering of this comparator.

thenComparing(): Returns a lexicographic-order comparator with another comparator. If this Comparator considers two elements equal, i.e. compare(a, b) == 0, other is used to determine the order.

Each step creates a new comparator based on the previous one. So the reversed() method creates a reversed comparator of

Comparator.comparingInt(Amount::getLineNum).thenComparingInt(Amount::getStartIndex)

To get only the second one reversed you should wrap it in an own comparator:

.thenComparing(Comparator.comparingInt(Amount::getStartIndex).reversed())

In your second solution the result is correct, because you are actually reversing the first condition twice:

Comparator.comparingInt(Amount::getLineNum).reversed() // reverses one time
    .thenComparingInt(Amount::getStartIndex).reversed() // reverses all before (also the first one)

So the complete solution would look like this:

Comparator.comparingInt(Amount::getLineNum)
    .thenComparing(Comparator.comparingInt(Amount::getStartIndex).reversed())
    .thenComparingDouble(Amount::getValue)
Top answer
1 of 5
218

This is a weakness in the compiler's type inferencing mechanism. In order to infer the type of u in the lambda, the target type for the lambda needs to be established. This is accomplished as follows. userList.sort() is expecting an argument of type Comparator<User>. In the first line, Comparator.comparing() needs to return Comparator<User>. This implies that Comparator.comparing() needs a Function that takes a User argument. Thus in the lambda on the first line, u must be of type User and everything works.

In the second and third lines, the target typing is disrupted by the presence of the call to reversed(). I'm not entirely sure why; both the receiver and the return type of reversed() are Comparator<T> so it seems like the target type should be propagated back to the receiver, but it isn't. (Like I said, it's a weakness.)

In the second line, the method reference provides additional type information that fills this gap. This information is absent from the third line, so the compiler infers u to be Object (the inference fallback of last resort), which fails.

Obviously if you can use a method reference, do that and it'll work. Sometimes you can't use a method reference, e.g., if you want to pass an additional parameter, so you have to use a lambda expression. In that case you'd provide an explicit parameter type in the lambda:

userList.sort(Comparator.comparing((User u) -> u.getName()).reversed());

It might be possible for the compiler to be enhanced to cover this case in a future release.

2 of 5
119

You can work around this limitation by using the two-argument Comparator.comparing with Comparator.reverseOrder() as the second argument:

users.sort(comparing(User::getName, reverseOrder()));
🌐
Javadevcentral
javadevcentral.com › comparator naturalorder, reverseorder and reversed
Comparator naturalOrder, reverseOrder and reversed | Java Developer Central
July 26, 2021 - In other words, using the sortByTotal ... sort the other way around (the highest total to lowest), we can call the reversed() method on the sortByTotal comparator as shown below....