Core Java

Java – Remove all nulls from a List

Introduction:

In this article, we’ll learn how to remove nulls from a Java List using plain-old Java, Java 8 lambda expression, and some third-party libraries.

So, let’s get started!

Removing nulls from a List In Java:

Let’s explore different ways in which we can remove nulls from a Java List:

1. Java 7 or lower versions:

When working with Java 7 or lower versions, we can use the below construct to remove all nulls from a List:

Note that we have created a mutable list here. Attempting to remove nulls from an immutable list will throw java.lang.UnsupportedOperationException.

2. Java 8 or higher versions:

The approach for removing nulls from a Java List for Java 8 or higher versions is pretty intuitive and elegant:

We can simply use the removeIf() construct to remove all null values.

If we don’t want to alter the existing list and rather return a new list with all non-null values, we can have:

We can learn more about Java 8 Stream Collectors here.

3. Apache Commons:

Apache Commons CollectionUtils class provides a filter(Iterable, Predicate) method that can also solve our purpose. The passed-in predicate is applied to all the elements in the list:

Thereby, filtering out all nulls from the existing list.

4. Google Guava:

The Iterables class in Guava provides removeIf(Iterable, Predicate) method to help us filter our values based on the given predicate. Let’s see how can we use it to our advantage:

Alternatively, if we don’t want to modify the existing list, Guava allows us to create a new filtered list:

Conclusion:

In this quick tutorial, we explored multiple ways in which we can remove all nulls from a List in Java.

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *