Without iterator
The easiest way is to use a for-each loop. Even in this case, you need to parameterize the record with the same wildcards as on this map. The reason is that Entry<? extends String, ? extends String> Entry<? extends String, ? extends String> Entry<? extends String, ? extends String> not a subtype of Entry<String, String> . The fact that String is a final class does not matter here, because the compiler does not know about it.
for (Entry<? extends String, ? extends String> entry : m.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); }
With iterator
If you really need an Iterator, the syntax that compiles is a bit perplexing:
Iterator<? extends Entry<? extends String, ? extends String>> iterator = m.entrySet().iterator(); while (iterator.hasNext()) { Entry<? extends String, ? extends String> entry = iterator.next(); String key = entry.getKey(); String value = entry.getValue(); }
I initially expected that the Iterator<Entry<? extends String, ? extends String>> Iterator<Entry<? extends String, ? extends String>> Iterator<Entry<? extends String, ? extends String>> , which is first represented by the return type of the iterator() method called in Set<Entry<? extends String, ? extends String>> Set<Entry<? extends String, ? extends String>> Set<Entry<? extends String, ? extends String>> , which in turn seems to be the return type of entrySet() called Map<? extends String, ? extends String> Map<? extends String, ? extends String> Map<? extends String, ? extends String> .
However, this is a bit more complicated. I found a likely answer here:
http://mail-archives.apache.org/mod_mbox/harmony-dev/200605.mbox/% 3Cbb4674270605110156r4727e563of9ce24cdcb41a0c8@mail.gmail.com % 3E
The interesting part:
The problem is that the entrySet() method returns Set<Map.Entry<capture-of ? extends K, capture-of ? extends V>> Set<Map.Entry<capture-of ? extends K, capture-of ? extends V>> Set<Map.Entry<capture-of ? extends K, capture-of ? extends V>> , which is incompatible with the type Set<Map.Entry<? extends K, ? extends V>> Set<Map.Entry<? extends K, ? extends V>> Set<Map.Entry<? extends K, ? extends V>> . Itβs easier to describe why if I omit the extends K and extends V parts. So, we have Set<Map.Entry<?, ?> And Set<Map.Entry<capture-of ?, capture-of ?>> .
First, Set<Map.Entry<?, ?>> is a set of Map.Entries of different types - i.e. This is a diverse collection. It can contain Map.Entry<Long, Date> and a Map.Entry<String, ResultSet>> and any other pair of types, all in one set.
On the other hand, Set<Map.Entry<capture-of ?, capture-of ?>> is a homogeneous collection of the same (albeit unknown) pair of types. For example, it could be Set<Map.Entry<Long, Date>> , so all records in the set MUST be Map.Entry<Long, Date> .