Sort List in Reverse Order in Java

In this post, we will discuss several ways to sort list in reverse order in Java. The given list is modifiable, but not necessarily resizable.


 

1. Collections.sort()

The java.util.Collections utility class provides 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():

 

1. Collections.sort() + Collections.reverse()

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

Java

Download   Run Code

Output:

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

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.

Java

Download   Run Code

Output:

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

3. Using Custom Comparator

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

Java

Download   Run Code

Output:

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

 

2. List.sort()

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

Java

Download   Run Code

Output:

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

 

3. Java 8

We can sort a list in reverse order using Stream API in Java 8 if all elements of the list are mutually Comparable. Below 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().
     

Java

Download   Run Code

Output:

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

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz