This post will discuss how to remove null values from a map in Java using plain Java, Guava library, and Apache Commons Collections.

Many operations on the 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. Using Map.remove() method

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

To remove all occurrences of null values from the map, we can get a 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. Using Map.removeAll() method

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. 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 – 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 Library

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

Download 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 Code

Output:

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

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

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

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

 
Suggested Read:

Filter null values from a Map in Java 8 and above