If you are using pre-Java 8, you can use:
Collection<String> values = map.values();
while (values.remove(null)) {}
This works because HashMap.values()
returns a view of the values, and:
The collection [returned by HashMap.values()
] supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations
An alternative way that might be faster, because you don't have to keep re-iterating the collection to find the first null element:
for (Iterator<?> it = map.values().iterator();
it.hasNext();) {
if (it.next() == null) {
it.remove();
}
}
Or you can do it without the explicit iteration:
values.removeAll(Collections.singleton(null));