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

2

37

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

Nones answered 25/2, 2009 at 11:36 Comment(0)
C
89

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
}

This version works with every Java version that supports generic (i.e. Java 5 and up).

Java 10 simplified that by letting variable types be inferred using var:

for (var entry : map.entrySet()) {
  var key = entry.getKey();
  var value = entry.getValue();
  // do stuff
}

While the previous two options are basically equivalent at the bytecode level, Java 8 also introduced forEach which uses lambdas* and works slightly difference. It invokes the lambda for each entry, which might add some overhead of those calls, if it's not optimized away:

map.forEach((k, v) -> { 
  // do stuff 
});

* technically the BiConsumer can also be implemented using a normal class, but it's intended for and mostly used with lambdas.

Chemisette answered 25/2, 2009 at 11:39 Comment(0)
M
1

While Joachim Sauer is correct for Java 5, there is a simpler option available starting at Java 10:

for (var entry : map.entrySet()) {
    // Do something with entry.getKey() and entry.getValue();
}

and Java 8 introduced:

map.forEach((k, v) -> {
    // Do something with k, v
});
Mayemayeda answered 7/8, 2023 at 13:36 Comment(5)
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 :-/Coronagraph
@Coronagraph "in Java 5 and higher". 1st is more readable. 2nd will for newer versions.Mayemayeda
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)Coronagraph
@Coronagraph 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.Asynchronism
While the question may mention Java 5, it also mentioned higher versions. Since this was the oldest question with the highest number of votes, it was the first I was offered when doing a search. Although this answer does not provide a Java 5 answer, it does answer the part of the question related to both easier and higher, since higher versions of Java do provide an easier option than Java 5 does. I can't help but think that the effort which went into criticising this answer, could have, instead, gone into improving it.Beffrey

© 2022 - 2024 — McMap. All rights reserved.