36

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

flybywire
  • 261,858
  • 191
  • 397
  • 503

2 Answers2

88

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
}
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
-1
for (var entry : map.entrySet())
    {
        // Do something with entry.getKey() and entry.getValue();
    }

Or simply use:

map.forEach((k, v) -> {
// Do something with k, v
});
user123123
  • 41
  • 6
  • 2
    BTW 1st snippet similar to already suggested one, in accepted answer (from 2009, >24 years ago) but with less details (as posted here, works only with Java 10 or later; question asking for Java 5); (ii) 2nd will not work with Java 5, 6, or 7 :-/ – user16320675 Aug 07 '23 at 14:25
  • @user16320675 "in Java 5 and higher". 1st is more readable. 2nd will for newer versions. – user123123 Aug 09 '23 at 15:43
  • so it will work with Java 5? is my comment wrong? (I think it isn't bad to give some advice to someone reading this answer... even if Java 5 is very old, Java 8 is still being used) – user16320675 Aug 09 '23 at 15:55
  • You appear to exhibit a demeanor akin to an enthusiastic and competitive canine, determined to showcase its abilities superior to others. – user123123 Aug 09 '23 at 16:01
  • @user16320675 is right. Your first answer is less detailed, and your second one is **incorrect**! The `.forEach()` method was only made available in Java 8 or newer as part of the [Java 8 Collections Improvements](https://www.javadevjournal.com/java/java-collections/#:~:text=Java%208%20and%20Collections%20Improvements). – Diego Borba Aug 09 '23 at 16:28