Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing null references from a HashSet

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)) ?

like image 514
Mouna Cheikhna Avatar asked Sep 19 '11 08:09

Mouna Cheikhna


People also ask

How do I remove a HashSet 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) .

How do you clean a HashSet?

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.


1 Answers

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.

like image 103
Joachim Sauer Avatar answered Oct 13 '22 21:10

Joachim Sauer