Course – LS – All
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

Sorting a collection that contains null values can lead to a NullPointerException if not handled properly. Java 8 has a convenient method Comparator.nullsLast() to address this issue. This method allows handling null values during sorting operations.

In this tutorial, we’ll learn how to use Comparator.nullsLast() to avoid NullPointerException when sorting in Java.

2. Understanding the Problem

Let’s create a simple scenario where we attempt to sort a list containing null values without proper exception handling:

List<String> strings = new ArrayList<>();
strings.add("BB");
strings.add("AA");
strings.add(null);
strings.add("EE");
strings.add("DD");

Collections.sort(strings);

In the above code, Collections.sort() encounters a null element during sorting. It throws a NullPointerException because null cannot be compared using the natural ordering of String.

Running this code results in the following exception:

Exception in thread "main" java.lang.NullPointerException
    at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:325)
    at java.util.ComparableTimSort.sort(ComparableTimSort.java:188)
    at java.util.Arrays.sort(Arrays.java:1312)
    at java.util.Arrays.sort(Arrays.java:1506)
    at java.util.ArrayList.sort(ArrayList.java:1464)
    at java.util.Collections.sort(Collections.java:143)
    at Main.main(Main.java:14)

This exception occurs because the default sorting behavior of Collections.sort() assumes that all sorted elements are Comparable, and null isn’t a valid Comparable object.

Now, let’s look at the solution using Comparator.nullsLast() to handle null values gracefully during sorting.

3. Using Comparator.nullsLast()

The Comparator.nullsLast() method is part of the Comparator interface introduced in Java 8. When sorting objects, it returns a comparator that considers null values as greater than non-null values. This is particularly useful when we want to sort a collection of objects based on a field that might be null, ensuring that null values are positioned at the end of the sorted list.

Let’s consider a practical example with a list of String strings that includes null values:

List<String> strings = new ArrayList<>();
strings.add("DD");
strings.add("BB");
strings.add(null);
strings.add("AA");
strings.add("EE");

We want to sort this list alphabetically while ensuring that null values are placed at the end of the sorted list.

So, after creating the list, we create a Comparator<String>, and using Comparator.nullsLast(Comparator.naturalOrder()), the string objects get stored in natural order while treating null values as greater than any non-null values:

Comparator<String> nullsLastComparator = Comparator.nullsLast(Comparator.naturalOrder());

Then, when we apply Collections.sort(), the list gets sorted with null values positioned at the end of the sorted list:

Collections.sort(strings, nullsLastComparator);

As a result, the sorting behavior becomes more predictable when dealing with collections that may contain null values, maintaining a consistent order based on our sorting criteria.

4. Conclusion

In this article, we explored the power of Comparator.nullsLast(). It allows us to sort data safely and predictably, enhancing the robustness and reliability of our sorting operations. Incorporating this method into our Java projects to handle null values effectively helps in maintaining code clarity and simplicity.

The source code of all these examples is available over on GitHub.

Course – LS – All
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

res – REST with Spring (eBook) (everywhere)
Subscribe
Notify of
guest
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments