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