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.

Answer from Lucky on Stack Overflow
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);
    }
}
🌐
Baeldung
baeldung.com › home › java › guide to java comparator.comparing()
Guide to Java Comparator.comparing() | Baeldung
January 8, 2024 - So let’s modify the test above. We’ll override the natural order of sorting by the name field by providing a Comparator for sorting the names in descending order as the second argument to Comparator.comparing:
🌐
Medium
medium.com › @AlexanderObregon › javas-comparator-reverseorder-method-explained-9f9b8bebd87b
Java’s Comparator.reverseOrder() Method Explained | Medium
January 26, 2025 - By combining the natural ordering logic of the Comparable interface with Comparator.reverseOrder(), you can sort objects in descending order based on a field, such as scores or dates.
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)
I managed to do this just fine in Data's compareTo() method, but now I'm trying to convert it to use Comarator. It mostly works but I can't figure out how to do the natural/reversed based on a value. Note that because the Data is sorted first by "ascending", by the time it needs to determine natural/reversed both arguments will be the same, either both natural or both reversed. ... JavaRanch-FAQ HowToAskQuestionsOnJavaRanch UseCodeTags DontWriteLongLines ItDoesntWorkIsUseLess FormatCode JavaIndenter SSCCE API-17 JLS JavaLanguageSpecification MainIsAPain KeyboardUtility
🌐
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(Shop s1, Shop s2) { return s1.name.compareTo(s2.name); } Descending Order public int compare(Shop s1, Shop s2) { return s2.name.compareTo(s1.name); } ... // Java Program to sort the ArrayList // in descending ...
🌐
LabEx
labex.io › tutorials › java-comparator-and-comparable-117394
Mastering Java Comparator and Comparable | LabEx
The first sorting shows students in descending order by GPA, and the second sorting shows students in reverse alphabetical order by name. Let's create one more example that combines multiple criteria and reverse ordering.
Find elsewhere
🌐
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
I suggested them because it was words like in the javadoc that caused the confusion of the @OKruger in the first place. ... 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.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Comparator.html
Comparator (Java Platform SE 8 )
October 20, 2025 - Caution should be exercised when using a comparator capable of imposing an ordering inconsistent with equals to order a sorted set (or sorted map). Suppose a sorted set (or sorted map) with an explicit comparator c is used with elements (or keys) drawn from a set S.
🌐
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.
🌐
Benchresources
benchresources.net › home › java › java 8 – comparator.comparing() method for custom/reverse sorting
Java 8 – Comparator.comparing() method for custom/reverse sorting - BenchResources.Net
October 18, 2021 - Sorting :- we are going to sort the Product list in the descending order of its quantity using Collections.sort() method passing reverse Comparator as 2nd argument and original list as 1st argument ... package net.bench.resources.comparator.comparing.custom; import java.util.Arrays; import ...
🌐
TutorialsPoint
tutorialspoint.com › sort-java-vector-in-descending-order-using-comparator
Sort Java Vector in Descending Order using Comparator
Collections.sort( nameOfcollection, ... objects in it by using the ?add()' method. Then, use the Comparator object and ?Collection.sort()' method to sort the vector in descending order....
🌐
How to do in Java
howtodoinjava.com › home › collections framework › java arraylist › java arraylist sort: ascending and descending order
Java ArrayList Sort: Ascending and Descending Order
August 4, 2023 - Learn to sort Java ArrayList in ascending and descending order using ArrayList.sort(), Collections.sort(), Comparator interface and Java 8 Streams.
🌐
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.
🌐
W3Schools
w3schools.com › java › java_advanced_sorting.asp
Java Advanced Sorting (Comparator and Comparable)
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Server Java Syllabus Java Study Plan Java Interview Q&A Java Certificate ... In the List Sorting Chapter, you learned how to sort lists alphabetically and numerically, but what if the list has objects in it? To sort objects you need to specify a rule that decides how objects should be sorted. For example, if you have a list of cars you might want to sort them by year, the rule could be that cars with an earlier year go first. The Comparator and Comparable interfaces allow you to specify what rule is used to sort objects.
🌐
GeeksforGeeks
geeksforgeeks.org › java › comparator-reverseorder-method-in-java-with-examples
Comparator reverseOrder() method in Java with examples - GeeksforGeeks
July 11, 2025 - ... // Java program to demonstrate // Comparator.reverseOrder() method import java.util.Arrays; import java.util.Comparator; import java.util.List; public class GFG { public static void main(String...
🌐
Oreate AI
oreateai.com › blog › mastering-descending-order-a-deep-dive-into-javas-comparator-and-comparingdate › b0b13d77802a4667e14d9b5840c0b50b
Mastering Descending Order: A Deep Dive Into Java's Comparator and `comparingDate` - Oreate AI Blog
1 week ago - For descending order, if date A is later than date B, our comparator should tell the sorting algorithm that A comes before B. Java 8 introduced some incredibly handy static methods on the Comparator interface, and Comparator.comparing() is a ...
🌐
iO Flood
ioflood.com › blog › java-comparator
Java Comparator Interface: Sorting with Comparator
February 20, 2024 - Finally, we chain another comparator that compares students by their name. This results in the students being sorted first by grade (in descending order), and then by name (in ascending order) if the grades are equal. Java 8 introduced streams, which provide a powerful way to process collections of data.