In this article we’ll consider different ways iterate over each entry in a Java Map.

Most efficient way to iterate Map:

Map<String, String> map = ...
for (Map.Entry<String, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + "/" + entry.getValue());
}

Using iterator and Map.Entry

long i = 0;
Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry<Integer, Integer> pair = it.next();
    i += pair.getKey() + pair.getValue();
}

Using foreach and Map.Entry

long i = 0;
for (Map.Entry<Integer, Integer> pair : map.entrySet()) {
    i += pair.getKey() + pair.getValue();
}

Using forEach from Java 8

final long[] i = {0};
map.forEach((k, v) -> i[0] += k + v);

Using keySet and foreach

long i = 0;
for (Integer key : map.keySet()) {
    i += key + map.get(key);
}

Using keySet and iterator

long i = 0;
Iterator<Integer> itr2 = map.keySet().iterator();
while (itr2.hasNext()) {
    Integer key = itr2.next();
    i += key + map.get(key);
}

Using for and Map.Entry

long i = 0;
for (Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); entries.hasNext(); ) {
    Map.Entry<Integer, Integer> entry = entries.next();
    i += entry.getKey() + entry.getValue();
}

Using the Java 8 Stream API

final long[] i = {0};
map.entrySet().stream().forEach(e -> i[0] += e.getKey() + e.getValue());

Using the Java 8 Stream API parallel

final long[] i = {0};
map.entrySet().stream().parallel().forEach(e -> i[0] += e.getKey() + e.getValue());

Leave a Reply

Your email address will not be published.