How do I efficiently iterate over each entry in a Java Map?

  • Post author:
  • Post category:Guides
  • Post last modified:July 7, 2021
  • Reading time:2 mins read

Solution

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()); 

Using IterableMap of Apache Collections

 long i = 0;
 MapIterator<Integer, Integer> it = iterableMap.mapIterator();
 while (it.hasNext()) {
     i += it.next() + it.getValue();
 } 

Using MutableMap of Eclipse (CS) collections

 final long[] i = {0};
 mutableMap.forEachKeyValue((key, value) -> {
     i[0] += key + value;
 });