This section provides code and benchmarks for ten unique example implementations which iterate over the entries of a Map<Integer, Integer> and generate the sum of the Integer values. All of the examples have an algorithmic complexity of Θ(n), however, the benchmarks are still useful for providing insight on which implementations are more efficient in a “real world” environment.

  1. Implementation using Iterator with Map.Entry
Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry<Integer, Integer> pair = it.next();
    sum += pair.getKey() + pair.getValue();
}
  1. Implementation using for with Map.Entry
for (Map.Entry<Integer, Integer> pair : map.entrySet()) {
    sum += pair.getKey() + pair.getValue();
}
  1. Implementation using Map.forEach (Java 8+)

map.forEach((k, v) -> sum[0] += k + v);

  1. Implementation using Map.keySet with for
for (Integer key : map.keySet()) {
    sum += key + map.get(key);
}
  1. Implementation using Map.keySet with Iterator
Iterator<Integer> it = map.keySet().iterator();
while (it.hasNext()) {
    Integer key = it.next();
    sum += key + map.get(key);
}
  1. Implementation using for with Iterator and Map.Entry
for (Iterator<Map.Entry<Integer, Integer>> entries = 
         map.entrySet().iterator(); entries.hasNext(); ) {
    Map.Entry<Integer, Integer> entry = entries.next();
    sum += entry.getKey() + entry.getValue();
}
  1. Implementation using Stream.forEach (Java 8+)

map.entrySet().stream().forEach(e -> sum += e.getKey() + e.getValue());

  1. Implementation using Stream.forEach with Stream.parallel (Java 8+)
map.entrySet()
   .stream()
   .parallel()
   .forEach(e -> sum += e.getKey() + e.getValue());
  1. Implementation using IterableMap from Apache Collections
MapIterator<Integer, Integer> mit = iterableMap.mapIterator();
while (mit.hasNext()) {
    sum += mit.next() + it.getValue();
}
  1. Implementation using MutableMap from Eclipse Collections