This post will discuss several ways to sort the list in ascending order in Java. Assume the specified list is modifiable but not necessarily resizable.

1. Using Collections.sort() method

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

Download  Run Code

Output:

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

 
This method will produce a stable sort. This will work only if all the list elements implement 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. 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:

[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. Using Java 8

Sorting a List became even easier with an introduction of Stream in Java 8 and above. The idea is to get a stream consisting of the elements of the list, sort it in natural order using the 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.

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, the following code creates a list of User and since User class doesn’t implement Comparable, the program will throw a Compilation error on calling Collections.sort() and a ClassCastException on List.sort(null).

Download Code

 
There are several ways to sort a list of Objects:

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

Download  Run Code

Output:

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

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

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.

Download  Run Code

Output:

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

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