How to sort List in descending order using Comparator in Java

Java 8Object Oriented ProgrammingProgramming

Let us first create an ArrayList −

ArrayList<Integer>arrList = new ArrayList<Integer>();
arrList.add(10);
arrList.add(50);
arrList.add(100);
arrList.add(150);
arrList.add(250);

Use Comparators interface to order in reverse order with reverseOrder() −

Comparator comparator = Collections.reverseOrder();
Now, sort with Collections:
Collections.sort(arrList, comparator);

Example

 Live Demo

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Demo {
   public static void main(String[] args) {
      ArrayList<Integer>arrList = new ArrayList<Integer>();
      arrList.add(10);
      arrList.add(50);
      arrList.add(100);
      arrList.add(150);
      arrList.add(250);
      arrList.add(100);
      arrList.add(150);
      arrList.add(250);
      Comparator comparator = Collections.reverseOrder();
      System.out.println("List = "+arrList);
      Collections.sort(arrList, comparator);
      System.out.println("Sorted List in descending order = "+arrList);
   }
}

Output

List = [10, 50, 100, 150, 250, 100, 150, 250]
Sorted List in descending order = [250, 250, 150, 150, 100, 100, 50, 10]
raja
Published on 23-Apr-2019 12:23:32
Advertisements