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.

Declaration − The java.util.Collections.reverseOrder() method is declared as follows -

public static <T>Comparator<T> reverseOrder()

Let us see a program to sort an ArrayList in Descending order using Comparator  with Java Collections −

Example

 Live Demo

import java.util.*;
public class Example {
   public static void main (String[] args) {
      ArrayList<Integer> list = new ArrayList<Integer>();
      list.add(10);
      list.add(50);
      list.add(30);
      list.add(20);
      list.add(40);
      list.add(60);
      System.out.println("Original list : " + list);
      Comparator c = Collections.reverseOrder();
      Collections.sort(list,c);
      System.out.println("Sorted list using Comparator : " + list);
   }
}

Output

Original list : [10, 50, 30, 20, 40, 60]
Sorted list using Comparator : [60, 50, 40, 30, 20, 10]

Updated on: 29-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements