If you’re only interested in the keys, you can iterate through the keySet() of the map:
Map
for (String key : map.keySet()) {
// …
}
If you only need the values, use values():
for (Object value : map.values()) {
// …
}
Finally, if you want both the key and value, use entrySet():
for (Map.Entry
String key = entry.getKey();
Object value = entry.getValue();
// …
}
One caveat: if you want to remove items mid-iteration, you’ll need to do so via an Iterator (see karim79’s answer). However, changing item values is OK (see Map.Entry).
Iterate through the entrySet() like so:
public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + ” = ” + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}
Read more about Map.