This post will discuss several ways to sort a list in reverse order in Java. The given list is modifiable but not necessarily resizable.

1. Using Collections.sort() method

The java.util.Collections utility class provides a static sort() method that sorts the specified list according to the order induced by the specified comparator. It sorts the specified list according to the natural ordering of its elements if no comparator is specified.

There are several methods to reverse a list using Collections.sort():

Collections.sort() with Collections.reverse()

Here, we simply sort the list in the natural order and reverse it to obtain the reverse sorted order.

Download  Run Code

Output:

[10, 8, 6, 5, 4, 2]

⮚ Using Reverse Order Comparator

For sorting the list in reverse order, we can pass a comparator to Collections.sort() that imposes the reverse of the natural ordering.

Download  Run Code

Output:

[10, 8, 6, 5, 4, 2]

⮚ Using Custom Comparator

We can also implement our own Comparator to sort the list in reverse order, as shown below:

Download  Run Code

Output:

[10, 8, 6, 5, 4, 2]

2. Using List.sort() method

Every List implementation provides a static sort() method that sorts the list according to the order induced by the specified Comparator. For this method to work, all the list elements must be mutually comparable using the specified comparator.

Download  Run Code

Output:

[10, 8, 6, 5, 4, 2]

3. Using Java 8

We can sort a list in reverse order using Stream in Java 8 and above if all the list elements are mutually Comparable. Following are the steps:

  1. Obtain a stream consisting of all elements of the list.
  2. Sort the stream in reverse order using Stream.sorted() method by passing Comparator.reverseOrder() to it that imposes the reverse of the natural ordering. We can also pass a lambda expression (a, b) -> b.compareTo(a) to Stream.sorted() method that defines the reverse sorting order.
  3. Collect all elements of sorted stream in a list using Stream.collect() with Collectors.toList().

The following program demonstrates it:

Download  Run Code

Output:

[10, 8, 6, 5, 4, 2]

That’s all about sorting a list in reverse order in Java.