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))
?
A HashSet , being a set, only contains one "copy" of any object, which also means that it can only contain one instance of null . Thus, you can just use HashSet. remove(null) .
HashSet. clear() method is used to remove all the elements from a HashSet. Using the clear() method only clears all the element from the set and not deletes the set. In other words, we can say that the clear() method is used to only empty an existing HashSet.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With