Sort ArrayList in descending order in Java

In one of the previous examples, we covered how to sort an ArrayList in ascending order.

In this post, you will learn how to sort ArrayList in descending order in Java.

We will explore the following ways:

  • Using the sort() method
  • Using the Collections.sort() and Collections.reverse() methods

Sort ArrayList in descending order in Java using the Collections.sort() method

We can use the sort() method from the List interface that accepts a Comparator and provide the Collections.reverseOrder() method as the method argument. If you’re new to interfaces in Java, be sure to check out our tutorial on Interface in Java for a deeper understanding.

In this way we get sorted list in reverse order.

Example

class Test {

  public static void main(String[] args) {
    List<String> list = new ArrayList<>(Arrays.asList("C", "A", "D", "B", "Z", "E"));

    list.sort(Collections.reverseOrder());

    System.out.println(list);
  }
}
Output: [Z, E, D, C, B, A]

Sort a List in Java in reverse order using the Collections.sort() and Collections.reverse() methods

Using this way, we first call a Collections.sort(), which is a static method in the Java Collections class that sorts a given list in ascending order and then we call the Collections.reverse() to get the list in a reverse order.

Example

class Test {

  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);

    List<String> list = new ArrayList<>(Arrays.asList("C", "A", "D", "B", "Z", "E"));

    Collections.sort(list);
    Collections.reverse(list);

    System.out.println(list);
  }
}
Output: [Z, E, D, C, B, A]

Leave a Reply

Your email address will not be published. Required fields are marked *