Remove nulls from a List in Java

In this post, we will see how to remove nulls from a List in Java using plain java, Guava library and Apache Commons Collections.

 

1. List.remove()

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

In order to remove all occurrences of null 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. List.removeAll()

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

Unlike remove() method, removeAll() will throw a NullPointerException if the specified collection is null. In order to remove all occurrences of nulls 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. We loop through the list using an iterator and remove all null elements from it.

 

Download   Run Code

Output:

[RED, BLUE, GREEN]

 

4. Using Guava

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

 

Download   Run 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

Output:

[RED, BLUE, GREEN]

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

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

 
Suggested Read: Remove null values from a List in Java 8

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz