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
🌐
Baeldung
baeldung.com › home › java › guide to java comparator.comparing()
Guide to Java Comparator.comparing() | Baeldung
January 8, 2024 - @Test public void whenComparingWithComparator_thenSortedByNameDesc() { Comparator<Employee> employeeNameComparator = Comparator.comparing( Employee::getName, (s1, s2) -> { return s2.compareTo(s1); }); Arrays.sort(employees, employeeNameComparator); assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc)); } As we can see, the results are sorted in descending order by name:
Top answer
1 of 3
22

What is logic behind ordering object elements? how "(this.grade - s.grade)" if positive 1 moves "this.grade" front and puts "s.grade" next in order, why not other way around?

Using negative numbers to say "this is less than that", positive numbers to say "this is more than that" and 0 to say "these 2 things are equal" has been in many computer languages for 30+ years.

Who validates the compare result (+1, -1, 0) and then puts in ascending order / descending order respectively, is there any documentation that describes internal working of this part?

There are several internal classes that use the return value to reorder elements in arrays or collections including

Collections.sort() Arrays.sort() TreeSet

EDIT

To answer HOW that works you will have to look at the source code for each of the classes I listed above. Some of them are quite complicated to try to make the sorting as efficient as possible. But in general, it all boils down to code like this:

Copyif( data[i].compareTo(data[j]) > 0 ){
   // swap data[i] and  data[j]
}
2 of 3
10

@DavidPrun Good question. I have tried explaining this with an example.

(x,y) -> (2, 5)

Ascending Order (x.compareTo(y)):

Copyif x.compareTo(y) == 1, then x > y , since y is smaller than x, you would have to move y in front of x.

2.compareTo(5) == 1 , Then don't move 5 in front of 2.

Descending Order (y.compareTo(x)):

Copyif y.compareTo(x) == 1, then y > x , since y is greater than x, you would have to move y in front of x.

5.compareTo(2) == -1 , Move 5 in front of 2.

Basically, we will always move y in front of x, if the result of compareTo method is 1.

🌐
Coderanch
coderanch.com › t › 743124 › java › sorting-Comparator-comparing
Problem sorting with Comparator.comparing() (Features new in Java 8 forum at Coderanch)
Seems to work... [ edit - ah, I now see it was already resolved. I like the "compStr = (a,b) -> a.str.compareTo( b.str ) * a.reverse;" better, nice!
🌐
Kotlin
kotlinlang.org › api › latest › jvm › stdlib › kotlin.comparisons › compare-by-descending.html
compareByDescending - Kotlin Programming Language
inline fun <T> compareByDescending( crossinline selector: (T) -> Comparable<*>? ): Comparator<T> (source) Creates a descending comparator using the function to transform value to a Comparable instance for comparison.
🌐
LabEx
labex.io › tutorials › java-comparator-and-comparable-117394
Mastering Java Comparator and Comparable | LabEx
Unsorted Student List: John, GPA: 3.5, Reg No: 101 Mary, GPA: 3.8, Reg No: 102 Alice, GPA: 3.5, Reg No: 103 Bob, GPA: 3.8, Reg No: 104 Charlie, GPA: 3.2, Reg No: 105 David, GPA: 3.2, Reg No: 106 Students sorted by complex criteria: (GPA descending, then name ascending, then reg. number descending) Bob, GPA: 3.8, Reg No: 104 Mary, GPA: 3.8, Reg No: 102 Alice, GPA: 3.5, Reg No: 103 John, GPA: 3.5, Reg No: 101 Charlie, GPA: 3.2, Reg No: 105 David, GPA: 3.2, Reg No: 106 ... This demonstrates how you can create complex, multi-level sorting logic by chaining comparators.
🌐
Kotlin
kotlinlang.org › api › core › kotlin-stdlib › kotlin.comparisons › compare-by-descending.html
compareByDescending | Core API – Kotlin Programming Language
inline fun <T> compareByDescending(crossinline selector: (T) -> Comparable<*>?): Comparator<T>(source) Creates a descending comparator using the function to transform value to a Comparable instance for comparison.
🌐
Medium
medium.com › @AlexanderObregon › javas-comparator-comparing-method-explained-342361288af6
Java’s Comparator.comparing() Method Explained | Medium
October 2, 2024 - // Sort by price in reverse order ... in descending order by their prices, with the “Laptop” listed first, followed by the “Smartphone,” and finally the “Tablet.” ·...
Find elsewhere
🌐
Kotlin
kotlinlang.org › api › latest › jvm › stdlib › kotlin.comparisons › then-by-descending.html
thenByDescending - Kotlin Programming Language
import kotlin.test.* fun main(args: Array<String>) { //sampleStart val list = listOf("aa", "b", "bb", "a") val lengthComparator = compareBy<String> { it.length } println(list.sortedWith(lengthComparator)) // [b, a, aa, bb] val lengthThenStringDesc = lengthComparator.thenByDescending { it } println(list.sortedWith(lengthThenStringDesc)) // [b, a, bb, aa] //sampleEnd }
Top answer
1 of 7
137

You can do the descending sort of a user-defined class this way overriding the compare() method,

Collections.sort(unsortedList,new Comparator<Person>() {
    @Override
    public int compare(Person a, Person b) {
        return b.getName().compareTo(a.getName());
    }
});

Or by using Collection.reverse() to sort descending as user Prince mentioned in his comment.

And you can do the ascending sort like this,

Collections.sort(unsortedList,new Comparator<Person>() {
    @Override
    public int compare(Person a, Person b) {
        return a.getName().compareTo(b.getName());
    }
});

Replace the above code with a Lambda expression(Java 8 onwards) we get concise:

Collections.sort(personList, (Person a, Person b) -> b.getName().compareTo(a.getName()));

As of Java 8, List has sort() method which takes Comparator as parameter(more concise) :

personList.sort((a,b)->b.getName().compareTo(a.getName()));

Here a and b are inferred as Person type by lambda expression.

2 of 7
71

For whats its worth here is my standard answer. The only thing new here is that is uses the Collections.reverseOrder(). Plus it puts all suggestions into one example:

/*
**  Use the Collections API to sort a List for you.
**
**  When your class has a "natural" sort order you can implement
**  the Comparable interface.
**
**  You can use an alternate sort order when you implement
**  a Comparator for your class.
*/
import java.util.*;

public class Person implements Comparable<Person>
{
    String name;
    int age;

    public Person(String name, int age)
    {
        this.name = name;
        this.age = age;
    }

    public String getName()
    {
        return name;
    }

    public int getAge()
    {
        return age;
    }

    public String toString()
    {
        return name + " : " + age;
    }

    /*
    **  Implement the natural order for this class
    */
    public int compareTo(Person p)
    {
        return getName().compareTo(p.getName());
    }

    static class AgeComparator implements Comparator<Person>
    {
        public int compare(Person p1, Person p2)
        {
            int age1 = p1.getAge();
            int age2 = p2.getAge();

            if (age1 == age2)
                return 0;
            else if (age1 > age2)
                return 1;
            else
                return -1;
        }
    }

    public static void main(String[] args)
    {
        List<Person> people = new ArrayList<Person>();
        people.add( new Person("Homer", 38) );
        people.add( new Person("Marge", 35) );
        people.add( new Person("Bart", 15) );
        people.add( new Person("Lisa", 13) );

        // Sort by natural order

        Collections.sort(people);
        System.out.println("Sort by Natural order");
        System.out.println("\t" + people);

        // Sort by reverse natural order

        Collections.sort(people, Collections.reverseOrder());
        System.out.println("Sort by reverse natural order");
        System.out.println("\t" + people);

        //  Use a Comparator to sort by age

        Collections.sort(people, new Person.AgeComparator());
        System.out.println("Sort using Age Comparator");
        System.out.println("\t" + people);

        //  Use a Comparator to sort by descending age

        Collections.sort(people,
            Collections.reverseOrder(new Person.AgeComparator()));
        System.out.println("Sort using Reverse Age Comparator");
        System.out.println("\t" + people);
    }
}
🌐
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 ...
🌐
TutorialsPoint
tutorialspoint.com › sort-arraylist-in-descending-order-using-comparator-with-java-collections
Sort ArrayList in Descending order using Comparator with Java Collections
In order to sort ArrayList in Descending order using Comparator, we need to use the Collections.reverseOrder() method which returns a comparator which gives the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
🌐
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.
🌐
Kotlin
kotlinlang.org › api › latest › jvm › stdlib › kotlin › -comparator
Comparator - Kotlin Programming Language
fun <T> Comparator<T>.thenByDescending( selector: (T) -> Comparable<*>? ): Comparator<T> Creates a descending comparator comparing values after the primary comparator defined them equal.
🌐
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
Your comparator is correct, and (depending on the language) it may wind up being used for other cases where the comparison should not be reversed. Instead of "fixing" (actually breaking) the comparator, you should find out how to get the sorter to sort in descending order.
🌐
Kotlin
kotlinlang.org › api › core › kotlin-stdlib › kotlin.comparisons › then-by-descending.html
thenByDescending
inline fun <T, K> Comparator<T>.thenByDescending(comparator: Comparator<in K>, crossinline selector: (T) -> K): Comparator<T>(source) Creates a descending comparator comparing values after the primary comparator defined them equal.
🌐
Medium
medium.com › @coffeeandtips.tech › using-comparator-comparing-to-sort-java-stream-a6e0302dce1a
Using Comparator.comparing to sort Java Stream | by Coffee and Tips | Medium
December 2, 2023 - Another important advantage of the Comparator.comparing interface is the ability to perform sorting in both ascending and descending order.
🌐
GeeksforGeeks
geeksforgeeks.org › java › sort-arraylist-in-descending-order-using-comparator-in-java
Sort ArrayList in Descending Order Using Comparator in Java - GeeksforGeeks
July 23, 2025 - Ascending Order public int compare(Item i1, Item i2) { if (i1.Property== i2.Property) return 0; else if (i1.Property > i2.Property) return 1; else return -1; } Descending Order public int compare(Item i1, Item i2) { if (i1.Property== i2.Property) return 0; else if (i1.Property < i2.Property) return 1; else return -1; }
🌐
Oreate AI
oreateai.com › blog › mastering-reverse-order-a-deep-dive-into-comparatorcomparingint-in-java › db8f23c62ea4f734c9d8289fd629e691
Mastering Reverse Order: A Deep Dive Into Comparator.comparingInt in Java - Oreate AI Blog
1 week ago - Then, you simply chain the .reversed() method onto it. It's like saying, "Sort by this integer, but then flip the whole result upside down." So, if you have a list of Person objects and you want to sort them by age in descending order, you'd ...