Skip to Content

Sort Java ArrayList in descending order using comparator example

  1. /*
  2.   Sort Java ArrayList in descending order using comparator example
  3.   This java example shows how to sort elements of Java ArrayList in descending order
  4.   using comparator and reverseOrder method of Collections class.
  5. */
  6.  
  7. import java.util.ArrayList;
  8. import java.util.Collections;
  9. import java.util.Comparator;
  10.  
  11. public class SortArrayListInDescendingOrderExample {
  12.  
  13.   public static void main(String[] args) {
  14.    
  15.     //create an ArrayList object
  16.     ArrayList arrayList = new ArrayList();
  17.    
  18.     //Add elements to Arraylist
  19.     arrayList.add("A");
  20.     arrayList.add("B");
  21.     arrayList.add("C");
  22.     arrayList.add("D");
  23.     arrayList.add("E");
  24.    
  25.     /*
  26.       To get comparator that imposes reverse order on a Collection use
  27.       static Comparator reverseOrder() method of Collections class
  28.     */
  29.    
  30.     Comparator comparator = Collections.reverseOrder();
  31.    
  32.     System.out.println("Before sorting ArrayList in descending order : "
  33.                                                               + arrayList);
  34.    
  35.     /*
  36.       To sort an ArrayList using comparator use,
  37.       static void sort(List list, Comparator c) method of Collections class.
  38.     */
  39.    
  40.     Collections.sort(arrayList,comparator);
  41.     System.out.println("After sorting ArrayList in descending order : "
  42.                                                               + arrayList);
  43.    
  44.   }
  45. }
  46.  
  47. /*
  48. Output would be
  49. Before sorting ArrayList in descending order : [A, B, C, D, E]
  50. After sorting ArrayList in descending order : [E, D, C, B, A]
  51. */