Get a HashSet out of the keys of a HashMap?

hashmap, hashset, java

Solution

Why do you specifically need a HashSet?

Any Set have the same interface, so typically can be used interchangeably, as good-practices requires that you use the Set interface for all of them.

If you really need so, you could create one from the other. For generic code, it could be:

    Map<B, V> map = ...;
    HashSet<B> set = new HashSet<B>(map.keySet());

Problem

I have a pretty big (100'000s of entries) `HashMap`. Now, I need a `HashSet` containing all the keys from this `HashMap`. Unfortunately, `HashMap` only has a `keySet()` method which returns a `Set` but not a `HashSet`. What would be an efficient way to generate such a `HashSet` using Java?

Original source