This post will discuss how to remove null values from a list using streams in Java.

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

1. Using Collection.removeIf() method

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 the removeIf() method, as shown below:

2. Using Java 8

We can use the 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]

 
This is equivalent to:

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. Map 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 replaces null values with a string.

Download  Run Code

Output:

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

 
This is equivalent to:

Download  Run Code

Output:

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

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