Filter null values from a Map in Java 8

In this post, we will see how to filter null values from a map using streams in Java.

 
In previous post, we have discussed how to filter null values from a map in Java using plain java, Guava library and Apache Commons Collections. In this post, we will discuss how to filter null values from a map using streams in Java 8.

 

1. Collection.removeIf()

Java 8 introduced several enhancements to the Collection interface, like 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 removeIf() method:

 

 

 

2. Java 8

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

Download   Run Code

Output:

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

 

3. Handle null map –

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

Download   Run Code

Output:

{}

 

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

 

Download   Run Code

Output:

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

 
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