Thursday, February 16, 2023

How to Sort a List in Reverse Order in Java? ArrayList Example

Java Collection Framework provides a convenient reverse comparator, to sort a List of objects in reverse order.  You can obtain reverse Comparator, by calling Collections.reverseOrder(), which by default sort List of Integer in reverse numeric order and List of String in reverse alphabetic order. It actually reverses the natural ordering of objects imposed by the Comparable interface. Apart from this method, Collections class also provides an overloaded method Collections.reverseOrder(Comparator cmp), which takes a Comparator, and sorts List on reverse order of that Comparator.


So next time if you need to sort your Collection in reverse order, you don’t need to write any extra comparator by yourself, you can directly leverage the reverse comparator provided by java.util.Collections class. 

It is as simple as calling Collections.sort() method providing comparator wrapped into Collections.reverseOrder() method. By using these two methods, you can sort any List implementation like ArrayList, LinkedList or Vector in Java.

How to Sort a List in Reverse Order in Java? ArrayList Example




Java Program to sort ArrayList in reverse Order

Here is the complete code for sorting List in reverse order in Java. In this Java program we have two lists, List<Integer> and List<String> and we are sorting them first in the natural order and then in their reverse order by using the Collections.reverseOrder() method.



import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
  * Java Program to sort List of object in reverse order. We will see examples of
  * sorting Array List in reverse order of both default ordering as well as any
  * custom ordering imposed by Compartor.
  *
  * @author Javin Paul
  */
public class CollectionSorting {
 
    private static final Logger logger = LoggerFactory.getLogger(CollectionSorting.class);
  
    public static void main(String args[]) {
      
        // Creating and initializing Collection to sort in reverse order
        // Integer will be sorted in reverse numeric order
        List<Integer> collection = new ArrayList<Integer>();
        collection.add(101);
        collection.add(201);
        collection.add(105);
        collection.add(302);
      
        logger.debug("Current order in Collection : " + collection);
      
        // Sorting Collection in reverse order
        Collections.sort(collection, Collections.reverseOrder());
      
        logger.debug("Sorted on Reverse order in Collection : {}", collection);
      
        // Sorting List of String in reverse Order
        List<String> alphabets = Arrays.asList("A", "B", "C", "D");
      
        logger.debug("Current order in List of String : {}", alphabets);
      
        // Sorting List in reverse Order
        Collections.sort(alphabets, Collections.reverseOrder());
      
        logger.debug("List of String sorted in reverse order {}", alphabets);
    }
 
}

Output
 [main] DEBUG CollectionSorting  - Current order in Collection : [101, 201, 105, 302]
 [main] DEBUG CollectionSorting  - Sorted on Reverse order in Collection : [302, 201, 105, 101]

[main] DEBUG CollectionSorting  - Current order in List of String : [A, B, C, D]
[main] DEBUG CollectionSorting  - List of String sorted in reverse order [D, C, B, A]



Java program to sort List in reverse orderThat's all on How to sort a List of Strings or Integers into reverse order. You can also use the same technique to sort any List into reverse order of their natural ordering or custom orders imposed by any Comparator in Java. With the new enhancements in Comparable and Comparator API in Java 8, you can even sort an ArrayList of object by multiple fields using comparing() and thenComparing() method. 



Other Java Collection tutorials you may like
  • 6 Advanced Comparator and Comparator Example for Sorting in Java (example)
  • How to sort a Map by keys and values in Java? (tutorial)
  • How to sort an ArrayList in ascending and descending order in Java? (tutorial)
  • Difference between ArrayList and HashSet in Java? (answer)
  • The difference between TreeMap and TreeSet in Java? (answer)
  • The difference between HashMap and ConcurrentHashMap in Java? (answer)
  • The difference between HashSet and TreeSet in Java? (answer)
  • The difference between ArrayList and LinkedList in Java? (answer)
  • The difference between Vector and ArrayList in Java? (answer)
Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions or feedback then please drop a comment.


3 comments :

Anonymous said...

Curly brackets are mistyped in the listing (as per the output).

Anonymous said...

For the sake of your life, stop using static fields, unless REALLY required

Unknown said...

Haha. Super clever comment for psv main method with test code

Post a Comment