Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a HashSet out of the keys of a HashMap?

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?

like image 347
Haes Avatar asked Oct 26 '09 16:10

Haes


1 Answers

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());
like image 52
KLE Avatar answered Sep 24 '22 20:09

KLE