Sort List in Ascending Order in Java

In this post, we will discuss several ways to sort List in ascending order in Java. Assume the specified list is modifiable, but not necessarily resizable.


 

1. Collections.sort()

Collections utility class provides static sort() method for sorting the specified list into ascending order, according to the natural ordering of its elements.

Java

Download   Run Code

Output:

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

This method will produce a stable sort. This will work only if all elements of the list implements the Comparable interface and are mutually comparable i.e. for any pair of elements (a, b) in the list, a.compareTo(b) does not throw a ClassCastException.

 

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:

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

If the specified comparator is null, then all elements in this list must implement the Comparable interface and the element’s natural ordering will be used.

 

3. Java 8

Sorting a List became even easier with a introduction of Stream API in Java 8. The idea is to get a stream consisting of the elements of the list, sort it in natural order using Stream.sorted() method and finally collect all sorted elements in a List using Stream.collect() with Collectors.toList(). For sorting to work, all elements of the list should be mutually Comparable.

Java

Download   Run Code

Output:

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

 

4. Sort List of Objects

Collections.sort(list) and list.sort(null) method will work only if all elements of the list implements the Comparable interface.

For example, below code creates a List of User and since User class doesn’t implements Comparable, the program will throw a Compilation error on calling Collections.sort() and a ClassCastException on List.sort(null).

Java

Download

There are several ways to sort an List of Objects –

1. Make the Object implement the Comparable interface and override the compareTo() method.

Java

Download   Run Code

Output:

[{Apple, 3}, {Google, 1}, {Microsoft, 2}]

2. Pass a Comparator to Collections.sort() method which defines how sorting of objects will take place in list.

Java

Download   Run Code

Output:

[{Google, 1}, {Microsoft, 2}, {Apple, 3}]

3. Pass Lambda expression to Collections.sort() method that defines list sorting order. This will work only on Java 8 and above.

Java

Download   Run Code

Output:

[{Google, 1}, {Microsoft, 2}, {Apple, 3}]

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of