How to Sort ArrayList in Descending order in java

I have already shared sorting of ArrayList in ascending order. In this post we will learn how to sort an ArrayList in descending order (decreasing order).

Read Also :  How to Synchronize ArrayList in Java with Example

Example of Sorting ArrayList in Descending order

To sort the ArrayList in descending order we will use two methods Collections.reverseOrder() method and Collections.sort() method.
One liner will be like :

Collections.sort(arraylist, Collections.reverseOrder());

Another way of sorting ArrayList in Descending order is to sort the list in ascending order first and then it will be reversed.
Collections.sort(list);
Collections.reverse(list);

Code of Sorting ArrayList in Descending Order 




import java.util.*;

 public class ArrayListDescendingSort {
    public static void main(String args[]) {
        
       ArrayList<String> arraylist = new ArrayList<String>();
    arraylist.add("Apple");
    arraylist.add("Banana");
    arraylist.add("Pear");
    arraylist.add("Mango");

    /*Unsorted List: ArrayList content before sorting*/
    System.out.println("ArrayList Before Sorting:");
    for(String str: arraylist){
   System.out.println(str);
  }

    /* Sorting in decreasing (descending) order*/
    Collections.sort(arraylist, Collections.reverseOrder());

    /* Sorted List in reverse order*/
    System.out.println("ArrayList in descending order:");
    for(String str: arraylist){
   System.out.println(str);
    }
  }
}


Output
ArrayList Before Sorting:
Apple
Banana
Pear
Mango
ArrayList in descending order:
Pear
Mango
Banana
Apple
Above example is to sort String ArrayList. Similarly, we can sort ArrayList of Integers in descending order.

import java.util.*;

 public class ArrayListDescendingSort2 {
    public static void main(String args[]) {
        
       ArrayList<Integer> arraylist = new ArrayList<Integer>();
    arraylist.add(1);
    arraylist.add(13);
    arraylist.add(89);
    arraylist.add(45);

    /*Unsorted List: ArrayList content before sorting*/
    System.out.println("ArrayList Before Sorting:");
    for(int num: arraylist){
   System.out.println(num);
  }

    /* Sorting in decreasing (descending) order*/
    Collections.sort(arraylist, Collections.reverseOrder());

    /* Sorted List in reverse order*/
    System.out.println("ArrayList in descending order:");
    for(int num: arraylist){
   System.out.println(num);
  }
  }
}


Output


ArrayList Before Sorting:
1
13
89
45
ArrayList in descending order:
89
45
13
1




About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry