[ACCEPTED]-Get a HashSet out of the keys of a HashMap?-hashset

Accepted answer
Score: 20

Why do you specifically need a HashSet?

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

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

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

Assuming that the word 'efficient' is the 9 key part of your question, and depending 8 what you want to do with the set, it might 7 be an idea to create your own subclass of 6 HashSet which ignores the HashSet implementation 5 and presents a view onto the existing map, instead.

As 4 a partially implemented example, it might 3 look something like:

public class MapBackedHashSet extends HashSet
    private HashMap theMap;

    public MapBackedHashSet(HashMap theMap)
        this.theMap = theMap;

    public boolean contains(Object o) 
        return theMap.containsKey(o);

    /* etc... */

If you don't know how 2 the class will be used, you'll need to take 1 care to override all the relevant methods.

Score: 4
HashSet myHashSet = new HashSet(myHashMap.keySet());

Haven't tried it.


Score: 3

Can you not create the HashSet from an existing 3 Set ? But (more importantly) why are you worried 2 about the implementation returned to you 1 from the keySet() method ?

Score: 2

Set set=new HashSet(map.keySet());


More Related questions