Remove null values from a Map in Java

In this post, we will see how to remove null values from a Map in Java using plain java, Guava library and Apache Commons Collections.

 
Many operations on map will throw a NullPointerException if any null values are present in it. There are many options to remove null values from a map:

 

1. Map.remove()

Collection.remove(Object) removes the first occurrence of the specified object from the collection. It returns true if object is removed from the collection and returns false if object is not present in the collection.

In order to remove all occurrences of null values from the map, we can get Collection of values from Map.values() and then continuously call remove(null) until all null values are removed.

 

Download   Run Code

Output:

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

 

2. Map.removeAll()

Map.values().removeAll(Collection) removes all elements contained in the specified collection from the Collection of values returned by Map.values().

The removeAll() method will throw a NullPointerException if the specified collection is null. In order to remove all occurrences of null values from the map, we can pass a singleton list or set containing only null.

 

Download   Run Code

Output:

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

 

3. Using Iterator

The idea is very simple. We loop through the map using an iterator and remove all mappings having null values.

 

Download   Run Code

Output:

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

 

4. Using Guava

Guava Iterables class provides removeIf(Iterable, Predicate) that removes every element from a specified iterable that satisfies the provided predicate.

 

Download   Run Code

Output:

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

 
We can also use lambda expressions in Java 8 and above:

 

5. Using Apache Commons Collections

Apache Commons Collections CollectionUtils class provides filter(Iterable, Predicate) that can filter the collection by applying specified Predicate to each element. If the predicate returns false, it removes the element.

 

Download

Output:

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

 
We can also use lambda expressions in Java 8 and above:

 
Apache Commons Collections also provides filterInverse(Iterable, Predicate) that works in similar way except it removes the element if the predicate returns true.

 
 
Suggested Read: Filter null values from a Map in Java 8

 
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