Removing null references from a HashSet

22,592

Solution 1

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.

Solution 2

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

Share:
22,592
Mouna Cheikhna
Author by

Mouna Cheikhna

Software Engineer at Microsoft Email : [email protected]

Updated on July 05, 2022

Comments

  • Mouna Cheikhna
    Mouna Cheikhna almost 2 years

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

  • Shimmy Weitzhandler
    Shimmy Weitzhandler about 4 years
    Is there a .NET alternative to a HashSet<string> that does not allow null values?