Removing null references from a HashSet

Mouna Cheikhna picture Mouna Cheikhna · Sep 19, 2011 · Viewed 19.3k times · Source

Is there a simple way of removing null references from a HashSet like the way we can delete them from a List using list.removeAll(Collections.singletonList(null)) ?

Answer

Joachim Sauer picture Joachim Sauer · Sep 19, 2011

Since a Set can not contain the same value twice (including null, if it is supported by the specific Set implementation), simply doing set.remove(null) would be sufficient.

Note that you don't even need to check for the existence of null before, because remove(null) will simply do nothing if the Set doesn't contain null.