Remove null values from a List in Java 8

In this post, we will see how to remove null values from a list using streams in Java 8.

 
In previous post, we have discussed how to remove null values from a list in Java using plain java, Guava library and Apache Commons Collections. In this post, we will discuss how to remove nulls from the list using streams in Java 8.

 

1. Collection.removeIf()

Java 8 introduced several enhancements to Collection interface, like removeIf() method. It removes all elements of the list that satisfy the given predicate.

To remove null values from a list, we can pass Objects.nonNull() to removeIf() method:

 

Download   Run Code

Output:

[RED, BLUE, GREEN]

 
There are many other ways to remove null values from a list using removeIf() method as shown below:

 

2. Java 8

We can use Stream.filter() method that returns a stream consisting of the elements that match the given predicate. We can specify a lambda expression or method reference to remove null values from the stream as shown below:

 

Download   Run Code

Output:

[RED, BLUE, GREEN]

 

3. Handle null list –

Calling stream() and removeIf() methods on a null list will throw a NullPointerException. We can avoid that by creating an empty list (if list is null) using Optional.ofNullable() as shown below:

 

Download   Run Code

Output:

[]

 

4. List the null values to a default value:

Instead of removing null values from a list, we can replace the null values with any custom value. To illustrate, the following example replace null values with a string.

 

Download   Run Code

Output:

[RED, ####, BLUE, ####, GREEN]

 
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