This post will discuss how we can filter null values from the stream in Java.

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 the current stream that match the given predicate. We can use the following lambda expression to filter null values from the stream:

 
We can also filter out the null values from the stream using the static nonNull() method provided by java.util.Objects. It returns true if the provided reference is non-null; otherwise, it 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 the following example, we’re replacing null values with an empty string.

Download  Run Code

Output:

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

That’s all about filtering null values from Stream in Java.