Filter null values from the Stream in Java 8

In this post, we will see how we can filter null values from the stream in Java 8.


 

Many operations on streams will throw a NullPointerException if any null values are present in it. There are many options to handle null values in a stream:

 

1. Filter null values:

We know that Stream.filter() returns a stream consisting of the elements of current stream that match the given predicate. We can use below lambda expression to filter null values from the stream:

 
We can also filter out the null values from the stream using static nonNull() method provided by java.util.Objects. It returns true if the provided reference is non-null otherwise returns false. There are two ways to call it:

1. Using Lambda expression:

2. Using method reference (recommended):

To illustrate, the following code creates a stream of cities from the String array (which contains few null values) and prints all non-null values:

 

Download   Run Code

Output:

NYC
Washington D.C.
Mexico
Fargo
Beijing
New Delhi
Tokyo

 

2. Map the null values to a default value:

Instead of filtering out null values from the stream completely, we can replace them with something. In below example, we’re replacing null values with an empty string.

 

Download   Run Code

Output:

NYC
Washington D.C.

Mexico
Fargo

Beijing
New Delhi
Tokyo

 
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