How to Sort a List in Java With Examples

Sometimes we have to sort a list in Java before processing its elements. In this tutorial, we will learn how to sort a list in the natural order. We will also learn how to use our own Comparator implementation to sort a list of objects.

Java List is similar to arrays except that the length of the list is dynamic and it comes in Java Collection framework. Actually, List is an interface and most of the time we use one of its implementation like ArrayList or LinkedList etc.

Java Sort List

Here we will learn how to sort a list of Objects in Java. We can use Collections.sort() method to sort a list in the natural ascending order. All the elements in the list must implement Comparable interface, otherwise IllegalArgumentException is thrown.

Let’s look at a quick example to sort a list of strings.

As you can see that we are using Collections.sort() method to sort the list of Strings. The String class implements Comparable interface.

Output:

java-sort-list

Java Sort List

Java Sort List of Objects

Let’s see another example where we will sort a list of custom objects. Note that the class must implement Comparable interface.

Output:

Sort a List in Java using Comparator

Collections.sort() method is overloaded and we can also provide our own Comparator implementation for sorting rules.

Since Comparator is a functional interface, we can use lambda expressions to write its implementation in a single line.

Output:

java-sort-list-objects-comparator

Java Sort List Objects – Comparator

Summary

Collections class sort() method is used to sort a list in Java. We can sort a list in natural ordering where the list elements must implement Comparable interface. We can also pass a Comparator implementation to define the sorting rules.

Reference: API Doc

By admin

Leave a Reply