How to filter “Null” values from HashMap? [duplicate]

You can use the Java 8 method Collection.removeIf for this purpose:

map.values().removeIf(Objects::isNull);

This removed all values that are null.

Online demo

This works by the fact that calling .values() for a HashMap returns a collection that delegated modifications back to the HashMap itself, meaning that our call for removeIf() actually changes the HashMap (this doesn’t work on all java Map’s)

Leave a Comment