What is the easiest way to iterate over all the key/value pairs of a java.util.Map in Java 5 and higher?

flybywire picture flybywire · Feb 25, 2009 · Viewed 24k times · Source

What is the easiest way to iterate over all the key/value pairs of a java.util.Map in Java 5 and higher?

Answer

Joachim Sauer picture Joachim Sauer · Feb 25, 2009

Assuming K is your key type and V is your value type:

for (Map.Entry<K,V> entry : map.entrySet()) {
  K key = entry.getKey();
  V value = entry.getValue();
  // do stuff
}