How to sort an ArrayList in Java in descending order?

Java 8Object Oriented ProgrammingProgramming

To sort the contents of an ArrayList in descending order

  1. Create an ArrayList.
  2. Sort the contents of the ArrayList using the sort() method of the Collections class.
  3. Then, reverse array list using the reverse() method of the Collections class.

Example:

import java.util.ArrayList;
import java.util.Collections;

public class ArrayListSample {
   public static void main(String[] args) {
      ArrayList<String> list = new ArrayList<String>();
      list.add("JavaFx");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      Collections.sort(list);
      System.out.println(list);
      Collections.reverse(list);
      System.out.println(list);
   }
}

Output:

[Java, JavaFx, OpenCV, WebGL]
[WebGL, OpenCV, JavaFx, Java]
raja
Published on 17-Jan-2018 10:43:46
Advertisements