This post will discuss how to filter null values from a map using streams in Java.

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

1. Using Collection.removeIf() method

Java 8 introduced several enhancements to the Collection interface, like the removeIf() method. It removes all mappings from the map that satisfy the given predicate.

To filter null values from the map, we can pass Objects.nonNull() to removeIf() method, as shown below:

Download  Run Code

Output:

{RED=#FF0000, BLUE=#0000FF, GREEN=#008000}

 
There are many other ways to filter null values from a map using the removeIf() method:

2. Using Java 8

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

Download  Run Code

Output:

{RED=#FF0000, BLUE=#0000FF, GREEN=#008000}

 
This is equivalent to:

Download  Run Code

Output:

{RED=#FF0000, BLUE=#0000FF, GREEN=#008000}

3. Handle null map

All the above codes will throw a NullPointerException if the map is null. We can avoid that by creating an empty map if the map is null using Optional.ofNullable(), as shown below:

Download  Run Code

4. Map the null values to a default value

Instead of removing mappings having null values from the map, 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=#FF0000, WHITE=#######, BLUE=#0000FF, BLACK=#######, GREEN=#008000}

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