What is the easiest way to iterate over all the key/value pairs of a java.util.Map in Java 5 and higher?
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.
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
});
.forEach()
method was only made available in Java 8 or newer as part of the Java 8 Collections Improvements. –
Asynchronism © 2022 - 2024 — McMap. All rights reserved.