简体   繁体   中英

Why can't we use Iterator on a Map(Java)?

I understand that to iterate through a Map , I need to use the entrySet() method and then use the Iterator on the resultant Set . I feel the question might be silly, but, how is the Map exactly implemented so that using an Iterator on it directly isn't possible? As far as I understand, Map isn't a collection, and Iterator is meant to be used over a collection. But logically, isn't Map also a collection of key-value pair(though it doesn't implement the Collection interface)?

AFAIK, You can't iterate over a Map directly because there are three types of iteration that a Map supports and there was no clear reason to choose one of the other. Doing the equivalent entrySet().iterator() may have been reasonable, but it's not the choice which was made.

Do you want to iterate the entries (key+value) or only keys or only values? That's why you obtain the specific collection and obtain an iterator.

Since keys/entries are unique (no duplicate elements present), you obtain a set through entrySet() and keySet() . And since values can have duplicates, you obtain the collection through values() and then get an iterator from these.

Collection implements Iterator, and Map though doesnt fall into java.util.Collection , its still considered in the Collection framework.

This is what i use to iterate a Map

for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

It depends on what value the programmer is seeking to iterate. Either it's just keys or values or both. based on that, we have three different objects that can be iterated. Example: mapObject.keySet().iterator() ; or mapObject.values().iterator() ; or mapObject.entrySet().iterator() . The only thing to keep in mind is that, when we iterate over just values() collection, we won't get respective keys by any means.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM