Java 8 Comparator – How to sort a List

In this article we’re going to see several examples on how to sort a List in Java 8.

1. Sort a List of String alphabetically

By purpose we’ve written London with “L” in low-case to better highlight difference between Comparator.naturalOrder() that returns a Comparator that sorts by placing capital letters first and String.CASE_INSENSITIVE_ORDER that returns a case-insensitive Comparator.

Basically in Java 7 we were using Collections.sort() that was accepting a List and, eventually, a Comparator –  in Java 8 we have the new List.sort() that accepts a Comparator.

2. Sort a List of Integer

3. Sort a List by String field

Let’s suppose we’ve our Movie class and we want to sort our List “by title”. We can use Comparator.comparing() and pass a function that extracts the field to use for sorting – title – in this example.

Output will be:

As you’ve probably noticed we haven’t passed any Comparator but the List is correctly sorted. That’s because title – the extracted field – is a String and String implements Comparable interface. If you peek at Comparator.comparing() implementation you will see that it calls compareTo on the extracted key.

4. Sort a List by double field

In a similar way we can use Comparator.comparingDouble() for comparing double value. In the example we want to order our List of Movie by rating, from the highest to the lowest.

We used reversed function on the Comparator in order to invert default natural-order that is from lowest to highest. Comparator.comparingDouble() uses under the hood.

If you need to compare int or long you can use comparingInt() and comparingLong() respectively.

5. Sort a List with custom Comparator

In the previous examples we haven’t specified any Comparator since it wasn’t necessary but let’s see an example in which we define our own Comparator. Our Movie class has a new field – “starred” – set using the third constructor parameter. In the example we want to sort the list so that we have starred movie at the top of the List. 

Result will be:

We can, of course, use Lambda expression instead of Anonymous class as follow:

And we can also use again Comparator.comparing():

In the latest example Comparator.comparing() takes as first parameter the function to extract the key to use for sorting and a Comparator as second parameter. This Comparator uses the extracted keys for comparison, star1 and star2 are indeed boolean and represents m1.getStarred() and m2.getStarred() respectively.

6. Sort a List with chain of Comparator

In the latest example we want to have starred movie at the top and then sort by rating.

And output is:

As you’ve seen we first sort by starred and then by rating – both reversed since we want highest value and true first.

One thought on “Java 8 Comparator – How to sort a List

Leave a Reply