Search code examples
javacollectionsforeachjava-5

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


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


Solution

  • 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.