About HashMap collection's keySet() method

408 Views Asked by At
Map<K, V> map = HashMap<K, V>();

Set<K> keySet = map.keySet(); //'map' is  parameter of HashMap object

Iterator<K> keyIterator = keySet.iterator();

I'm studying about how I can get key by 'Iterator'. The code above is part of that.

but [Set<K> keySet = map.keySet();] <- in this part

Isn't it that HashMap's keySet() method is what Set interface's keySet() method is redefined in HashMap?

but I can't find it in JAVA API document's method menu.

3

There are 3 best solutions below

0
user13784117 On BEST ANSWER

You seem to be making this more complicated than necessary.

A Map<K,V> has some keys; it will hand you a view of those keys as a Set<K>.

That Set<> necessarily implements the Set<> interface, which has Iterable<> as a subinterface. Therefore you can get an iterator over the Set.

Since it's an Iterator, then if you iterate it, it will eventually yield every possible key. That is:

while (iterator.hasNext()) {
     key = iterator.Next(); // <<< this is the key
      :
}

But what are you actually trying to do?

i'm studying about how i can get key by 'iterator' above is part of that

The point of the Map and Set interfaces is that you can access them directly by key.

0
0xh3xa On

The keySet() method returns a set of keys in the HashMap of type KeySet. The inner implementation in the HashMap implements AbstractSet and stores the keys into that set with the name of keySet.

The hierarchy of the implementations in the HashMap:

|---- Collection<E> extends Iterable<E>
|
|------- Set<E> extends Collection<E>
|
|------------ AbstractSet<E> extends AbstractCollection<E> implements Set<E>
|
|--------------- KeySet extends AbstractSet<K>
0
WJS On

You can certainly do that. But I have never had the need to get the keySet iterator. You can just do the following.

Map<String, Object> map = new HashMap<>();
// later
for (String key : map.keySet()) {
   // so something with keys (e.g) print them.
   System.out.println(key);
}

But you can also do this.

Iterator<String> it = map.keySet().iterator();
while(it.hasNext()) {
    System.out.println(it.next());
}