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.

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

With this way, we first call a Collections.sort() method to sort a list 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.