Filter null values from Stream in Java
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:
|
1 |
stream.filter(x -> x != null); |
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:
|
1 |
stream.filter(x -> Objects.nonNull(x)); |
2. Using method reference (recommended):
|
1 |
stream.filter(Objects::nonNull); |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.Arrays; import java.util.Objects; class Main { // Program to filter null values from a stream in Java 8 and above public static void main(String[] args) { String[] cities = { "NYC", "Washington D.C.", null, "Mexico", "Fargo", null, "Beijing", "New Delhi", "Tokyo" }; Arrays.stream(cities) .filter(Objects::nonNull) .forEach(System.out::println); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.util.Arrays; class Main { // Program to replace null values from a stream in Java 8 and above public static void main(String[] args) { String[] cities = { "NYC", "Washington D.C.", null, "Mexico", "Fargo", null, "Beijing", "New Delhi", "Tokyo" }; Arrays.stream(cities) .map(city -> (city == null ? "" : city)) .forEach(System.out::println); } } |
Output:
NYC
Washington D.C.
Mexico
Fargo
Beijing
New Delhi
Tokyo
That’s all about filtering null values from Stream in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)