How to sort an ArrayList in Descending Order in Java

Java 8Object Oriented ProgrammingProgramming

To sort an ArrayList, you need to use the Collections.sort() method. This sorts in ascending order, but if you want to sort the ArrayList in descending order, use the Collections.reverseOrder() method as well. This gets included as a parameter −

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

Following is the code to sort an ArrayList in descending order in Java −

Example

 Live Demo

import java.util.ArrayList;
import java.util.Collections;
public class Demo {
   public static void main(String args[]) {
      ArrayList<Integer> myList = new ArrayList<Integer>();
      myList.add(30);
      myList.add(99);
      myList.add(12);
      myList.add(23);
      myList.add(8);
      myList.add(94);
      myList.add(78);
      myList.add(87);
      System.out.println("Points\n"+ myList);
      Collections.sort(myList,Collections.reverseOrder());
      System.out.println("Points (descending order)\n"+ myList);
   }
}

Output

Points
[30, 99, 12, 23, 8, 94, 78, 87]
Points (descending order)
[99, 94, 87, 78, 30, 23, 12, 8]

Let us see another example wherein we will sort string values in descending order −

Example

 Live Demo

import java.util.ArrayList;
import java.util.Collections;
public class Demo {
   public static void main(String args[]) {
      ArrayList<String> myList = new ArrayList<String>();
      myList.add("Jack");
      myList.add("Katie");
      myList.add("Amy");
      myList.add("Tom");
      myList.add("David");
      myList.add("Arnold");
      myList.add("Steve");
      myList.add("Tim");
      System.out.println("Names\n"+ myList);
      Collections.sort(myList,Collections.reverseOrder());
      System.out.println("Names (descending order)\n"+ myList);
   }
}

Output

Names
[Jack, Katie, Amy, Tom, David, Arnold, Steve, Tim]
Names (descending order)
[Tom, Tim, Steve, Katie, Jack, David, Arnold, Amy]
raja
Published on 20-Sep-2019 11:11:23
Advertisements