This post will discuss how to remove nulls from a list in Java using plain Java, Guava library, and Apache Commons Collections.

1. Using List.remove() method

List.remove(Object) removes the first occurrence of the specified object from the list. It returns true if the object is removed from the list and returns false if it is not present in the list.

To remove all null occurrences from the list, we can continuously call remove(null) until all null values are removed. Please note that the list will remain unchanged if it does not contain any null value.

Download  Run Code

Output:

[RED, BLUE, GREEN]

2. Using List.removeAll() method

List.removeAll(Collection) removes elements contained in the specified collection from the list.

Unlike the remove() method, removeAll() will throw a NullPointerException if the specified collection is null. To remove all nulls occurrences from the list, we can pass a singleton list or set containing only null.

Download  Run Code

Output:

[RED, BLUE, GREEN]

3. Using Iterator

The idea is very simple – loop through the list using an iterator and remove all null elements from it.

Download  Run Code

Output:

[RED, BLUE, GREEN]

4. Using Guava Library

Guava’s Iterables class provides removeIf(Iterable, Predicate) that removes every element from a specified iterable that satisfies the provided predicate.

Download Code

Output:

[RED, BLUE, GREEN]

 
We can also use lambda expressions in Java 8 and above:

5. Using Apache Commons Collections

Apache Commons Collections CollectionUtils class provides filter(Iterable, Predicate) that can filter the collection by applying specified Predicate to each element. If the predicate returns false, it removes the element.

Download Code

Output:

[RED, BLUE, GREEN]

 
We can also use lambda expressions in Java 8 and above:

 
Apache Commons Collections also provides the filterInverse(Iterable, Predicate) that works similarly, except it removes the element if the predicate returns true.

That’s all about removing nulls from a List in Java.

 
Suggested Read:

Remove null values from a List in Java 8 and above