Sort items of an ArrayList with Collections.reverseOrder() in Java


In order to sort items of an ArrayList with Collections.reverseOrder() in Java, 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 with Collections.reverseOrder() in Java -

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);
      Collections.sort(list);
      System.out.println("Sorted list : " + list);
      Collections.sort(list,Collections.reverseOrder());
      System.out.println("Sorted list using Collections.reverseOrder() : " + list);
   }
}

Output

Original list : [10, 50, 30, 20, 40, 60]
Sorted list : [10, 20, 30, 40, 50, 60]
Sorted list using Collections.reverseOrder() : [60, 50, 40, 30, 20, 10]

Updated on: 25-Jun-2020

314 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements