Read the javadoc: Map<K, V>.forEach() expects a BiConsumer<? super K,? super V> as argument, and the signature of the BiConsumer<T, U> abstract method is accept(T t, U u).

So you should pass it a lambda expression that takes two inputs as argument: the key and the value:

map.forEach((key, value) -> {
    System.out.println("Key : " + key + " Value : " + value);
});

Your code would work if you called forEach() on the entry set of the map, not on the map itself:

map.entrySet().forEach(entry -> {
    System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}); 
Answer from JB Nizet on Stack Overflow
🌐
Medium
medium.com › @AlexanderObregon › javas-map-foreach-method-explained-0fe0dc60fa5e
Java's Map.forEach() Method Explained
December 7, 2024 - This example demonstrates how you can transform or process map values during iteration, creating new insights or outputs without altering the original map. Configuration data, often represented as a map of strings, can be processed effectively using forEach(). This is especially useful when loading and validating settings. import java.util.HashMap; import java.util.Map; public class ConfigProcessingExample { public static void main(String[] args) { Map<String, String> config = new HashMap<>(); config.put("host", "localhost"); config.put("port", "8080"); config.put("debug", "true"); config.forEach((property, value) -> { System.out.println("Property: " + property + ", Value: " + value); if (property.equals("port") && !value.matches("\\d+")) { System.out.println("Invalid port configuration: " + value); } }); } }
🌐
W3Schools
w3schools.com › java › ref_hashmap_foreach.asp
Java HashMap forEach() Method
Java Examples Java Videos Java ... Java Study Plan Java Interview Q&A · ❮ HashMap Methods · Use the forEach() method to print every entry in the map: import java.util.HashMap; public class Main { public static void ...
🌐
Mkyong
mkyong.com › home › java8 › java 8 foreach examples
Java 8 forEach examples | mkyong.com
December 4, 2020 - When I do this, I am getting a null pointer exception when the value in the map is null (v is null). How can I avoid that? items.forEach((k,v)->System.out.println(“Item : ” + k + ” Count : ” + v));
🌐
Baeldung
baeldung.com › home › java › java collections › java map › iterate over a map in java
Iterate Over a Map in Java | Baeldung
December 16, 2024 - Here, we are only interested in the values in the Map collection. After defining an iterator object from the Map, we iterate through the values and find their sum. Since version 8, Java supports the forEach() method and lambda expressions, which can be used with maps.
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › java foreach()
Java forEach() with Examples - HowToDoInJava
February 6, 2023 - Consumer<String> makeUpperCase ... System.out.println(t.toUpperCase()); } }; List<String> list = Arrays.asList("Alex", "Brian", "Charles"); list.forEach(makeUpperCase); ... When used with Map, forEach() method performs ...
Top answer
1 of 8
220

Read the javadoc: Map<K, V>.forEach() expects a BiConsumer<? super K,? super V> as argument, and the signature of the BiConsumer<T, U> abstract method is accept(T t, U u).

So you should pass it a lambda expression that takes two inputs as argument: the key and the value:

map.forEach((key, value) -> {
    System.out.println("Key : " + key + " Value : " + value);
});

Your code would work if you called forEach() on the entry set of the map, not on the map itself:

map.entrySet().forEach(entry -> {
    System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}); 
2 of 8
16

Maybe the best way to answer the questions like "which version is faster and which one shall I use?" is to look to the source code:

map.forEach() - from Map.java

default void forEach(BiConsumer<? super K, ? super V> action) {
    Objects.requireNonNull(action);
    for (Map.Entry<K, V> entry : entrySet()) {
        K k;
        V v;
        try {
            k = entry.getKey();
            v = entry.getValue();
        } catch(IllegalStateException ise) {
            // this usually means the entry is no longer in the map.
            throw new ConcurrentModificationException(ise);
        }
        action.accept(k, v);
    }
}

javadoc

map.entrySet().forEach() - from Iterable.java

default void forEach(Consumer<? super T> action) {
    Objects.requireNonNull(action);
    for (T t : this) {
        action.accept(t);
    }
}

javadoc

This immediately reveals that map.forEach() is also using Map.Entry internally. So I would not expect any performance benefit in using map.forEach() over the map.entrySet().forEach(). So in your case the answer really depends on your personal taste :)

For the complete list of differences please refer to the provided javadoc links. Happy coding!

🌐
JetBrains
jetbrains.com › help › inspectopedia › Java8MapForEach.html
'Map.forEach()' can be used | Inspectopedia Documentation
June 30, 2026 - Example · void print(Map<String, Integer> map) { map.entrySet().forEach(entry -> { String str = entry.getKey(); System.out.println(str + ":" + entry.getValue()); }); } void print(Map<String, Integer> map) { map.forEach((str, value) -> ...
🌐
Vultr
docs.vultr.com › java › standard-library › java › util › HashMap › forEach
Java HashMap forEach() - Apply Function to Items | Vultr Docs
November 19, 2024 - HashMap<String, Integer> map = new HashMap<>(); map.put("One", 1); map.put("Two", 2); map.put("Three", 3); map.forEach((key, value) -> System.out.println(key + " = " + value)); Explain Code · This code initializes a HashMap with some integer ...
Find elsewhere
🌐
Java67
java67.com › 2014 › 05 › 3-examples-to-loop-map-in-java-foreach.html
3 Examples to Loop Map in Java - Foreach vs Iterator | Java67
Since Map by default doesn't guarantee any order, any code which assumes a particular order during iteration will fail. You only want to traverse or loop through a Map, if you want to transform each mapping one by one. Now Java 8 release provides a new way to loop through Map in Java using Stream API and forEach method.
🌐
Programiz
programiz.com › java-programming › library › hashmap › foreach
Java HashMap forEach()
action - actions to be performed on each mapping of the HashMap · The forEach() method does not return any value. import java.util.HashMap; class Main { public static void main(String[] args) { // create a HashMap HashMap<String, Integer> prices = new HashMap<>(); // insert entries to the HashMap prices.put("Shoes", 200); prices.put("Bag", 300); prices.put("Pant", 150); System.out.println("Normal Price: " + prices); System.out.print("Discounted Price: "); // pass lambda expression to forEach() prices.forEach((key, value) -> { // decrease value by 10% value = value - value * 10/100; System.out.print(key + "=" + value + " "); }); } }
🌐
Java Guides
javaguides.net › 2019 › 11 › java-8-foreach-with-list-set-and-map.html
Java 8 forEach with List, Set and Map Examples
September 14, 2020 - public static void forEachWithMap() ... can loop a Map with forEach + lambda expression. map.forEach((k, p) -> { System.out.println(k); System.out.println(p.getName()); }); } The below example shows how to use the forEach method ...
🌐
CodeGym
codegym.cc › java blog › java collections › how to iterate a map in java
How to iterate a Map in Java
January 8, 2025 - This example filters out entries where the value is greater than 3 before processing them. map.entrySet().stream() .map(entry -> entry.getKey() + " has " + (entry.getValue() * 2) + " items") .forEach(System.out::println); Here, the map() operation ...
🌐
ZetCode
zetcode.com › java › hashmapiterate
Java HashMap iteration - learn how to iterate HashMap in Java
In the first example, we use the forEach method to iterate over the key-value pairs of the HashMap. The forEach method performs the given action for each element of the map until all elements have been processed or the action throws an exception. ... package com.zetcode; import java.util.HashMap; ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › iterate-map-java
How to Iterate Any Map in Java? - GeeksforGeeks
September 1, 2026 - Explanation: The forEach() method accepts an action that is performed for every key-value pair. Here, name represents the key and mark represents the value. Another way is to iterate through the keys using keySet() and retrieve the corresponding ...
🌐
BeginnersBook
beginnersbook.com › 2017 › 10 › java-8-foreach
Java 8 forEach method with example
In this guide, we will learn how ... main(String[] args) { Map<Integer, String> hmap = new HashMap<Integer, String>(); hmap.put(1, "Monkey"); hmap.put(2, "Dog"); hmap.put(3, "Cat"); hmap.put(4, "Lion"); hmap.put(5, "Tiger"); hmap.put(6, "Bear"); /* forEach to iterate and display ...
🌐
Mkyong
mkyong.com › home › java › how to loop map in java
How to loop Map in Java | mkyong.com
March 13, 2024 - LoopMap2.java · package ... "Jan"); map.put(2, "Feb"); map.put(3, "Mar"); // map.forEach((key, value) -> System.out.println("ID: " + key + ", Name: " + value)); map.forEach((id, name) -> { System.out.println("ID: " ...
🌐
Oodlestechnologies
oodlestechnologies.com › blogs › java-8-foreach-and-lambda-expression-for-map-and-list
Java 8 forEach and Lambda Expression For Map and List
February 14, 2020 - forEach loop, in Java 8, provides programmers a new, interesting and concise way of iterating over a Collection. Lambda expression is also a new and important feature of Java which was included in Java 8. It provides a concise and clear way to represent one method interface using an expression. It is also very useful in the collection library. The below code is a normal way to loop over a Map:
Top answer
1 of 16
5965
Map<String, String> map = ...
for (Map.Entry<String, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + "/" + entry.getValue());
}

On Java 10+:

for (var entry : map.entrySet()) {
    System.out.println(entry.getKey() + "/" + entry.getValue());
}
2 of 16
1632

To summarize the other answers and combine them with what I know, I found 10 main ways to do this (see below). Also, I wrote some performance tests (see results below). For example, if we want to find the sum of all of the keys and values of a map, we can write:

  1. 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();
    }
    
  2. Using foreach and Map.Entry

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

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

    long i = 0;
    for (Integer key : map.keySet()) {
        i += key + map.get(key);
    }
    
  5. 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);
    }
    
  6. 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();
    }
    
  7. Using the Java 8 Stream API

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

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

    long i = 0;
    MapIterator<Integer, Integer> it = iterableMap.mapIterator();
    while (it.hasNext()) {
        i += it.next() + it.getValue();
    }
    
  10. Using MutableMap of Eclipse (CS) collections

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

Perfomance tests (mode = AverageTime, system = Windows 8.1 64-bit, Intel i7-4790 3.60 GHz, 16 GB)

  1. For a small map (100 elements), score 0.308 is the best

    Benchmark                          Mode  Cnt  Score    Error  Units
    test3_UsingForEachAndJava8         avgt  10   0.308 ±  0.021  µs/op
    test10_UsingEclipseMap             avgt  10   0.309 ±  0.009  µs/op
    test1_UsingWhileAndMapEntry        avgt  10   0.380 ±  0.014  µs/op
    test6_UsingForAndIterator          avgt  10   0.387 ±  0.016  µs/op
    test2_UsingForEachAndMapEntry      avgt  10   0.391 ±  0.023  µs/op
    test7_UsingJava8StreamApi          avgt  10   0.510 ±  0.014  µs/op
    test9_UsingApacheIterableMap       avgt  10   0.524 ±  0.008  µs/op
    test4_UsingKeySetAndForEach        avgt  10   0.816 ±  0.026  µs/op
    test5_UsingKeySetAndIterator       avgt  10   0.863 ±  0.025  µs/op
    test8_UsingJava8StreamApiParallel  avgt  10   5.552 ±  0.185  µs/op
    
  2. For a map with 10000 elements, score 37.606 is the best

    Benchmark                           Mode   Cnt  Score      Error   Units
    test10_UsingEclipseMap              avgt   10    37.606 ±   0.790  µs/op
    test3_UsingForEachAndJava8          avgt   10    50.368 ±   0.887  µs/op
    test6_UsingForAndIterator           avgt   10    50.332 ±   0.507  µs/op
    test2_UsingForEachAndMapEntry       avgt   10    51.406 ±   1.032  µs/op
    test1_UsingWhileAndMapEntry         avgt   10    52.538 ±   2.431  µs/op
    test7_UsingJava8StreamApi           avgt   10    54.464 ±   0.712  µs/op
    test4_UsingKeySetAndForEach         avgt   10    79.016 ±  25.345  µs/op
    test5_UsingKeySetAndIterator        avgt   10    91.105 ±  10.220  µs/op
    test8_UsingJava8StreamApiParallel   avgt   10   112.511 ±   0.365  µs/op
    test9_UsingApacheIterableMap        avgt   10   125.714 ±   1.935  µs/op
    
  3. For a map with 100000 elements, score 1184.767 is the best

    Benchmark                          Mode   Cnt  Score        Error    Units
    test1_UsingWhileAndMapEntry        avgt   10   1184.767 ±   332.968  µs/op
    test10_UsingEclipseMap             avgt   10   1191.735 ±   304.273  µs/op
    test2_UsingForEachAndMapEntry      avgt   10   1205.815 ±   366.043  µs/op
    test6_UsingForAndIterator          avgt   10   1206.873 ±   367.272  µs/op
    test8_UsingJava8StreamApiParallel  avgt   10   1485.895 ±   233.143  µs/op
    test5_UsingKeySetAndIterator       avgt   10   1540.281 ±   357.497  µs/op
    test4_UsingKeySetAndForEach        avgt   10   1593.342 ±   294.417  µs/op
    test3_UsingForEachAndJava8         avgt   10   1666.296 ±   126.443  µs/op
    test7_UsingJava8StreamApi          avgt   10   1706.676 ±   436.867  µs/op
    test9_UsingApacheIterableMap       avgt   10   3289.866 ±  1445.564  µs/op
    

Graphs (performance tests depending on map size)

Table (perfomance tests depending on map size)

          100     600      1100     1600     2100
test10    0.333    1.631    2.752    5.937    8.024
test3     0.309    1.971    4.147    8.147   10.473
test6     0.372    2.190    4.470    8.322   10.531
test1     0.405    2.237    4.616    8.645   10.707
test2     0.376    2.267    4.809    8.403   10.910
test7     0.473    2.448    5.668    9.790   12.125
test9     0.565    2.830    5.952   13.220   16.965
test4     0.808    5.012    8.813   13.939   17.407
test5     0.810    5.104    8.533   14.064   17.422
test8     5.173   12.499   17.351   24.671   30.403

All tests are on GitHub.

🌐
GeeksforGeeks
geeksforgeeks.org › java › how-does-hashmap-foreach-method-work-in-java-8
How does HashMap forEach() Method Work in Java 8? - GeeksforGeeks
July 23, 2025 - The HashMap in Java stores the data in the form of a key-value pair. The HashMap takes the generic parameters for the key along with the value. Similarly, like we instantiate the classes in Java we also instantiate the hash map like we create objects in Java. In this article, we will be using the forEach() method.
Top answer
1 of 7
1425

I know I'm a bit late for that one, but I'll share what I did too, in case it helps someone else :

HashMap<String, HashMap> selects = new HashMap<String, HashMap>();

for(Map.Entry<String, HashMap> entry : selects.entrySet()) {
    String key = entry.getKey();
    HashMap value = entry.getValue();

    // do what you have to do here
    // In your case, another loop.
}
2 of 7
301

Lambda Expression Java 8

In Java 1.8 (Java 8) this has become lot easier by using forEach method from Aggregate operations(Stream operations) that looks similar to iterators from Iterable Interface.

Just copy paste below statement to your code and rename the HashMap variable from hm to your HashMap variable to print out key-value pair.

HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
/*
 *     Logic to put the Key,Value pair in your HashMap hm
 */

// Print the key value pair in one line.
hm.forEach((k,v) -> System.out.println("key: "+k+" value:"+v));

Here is an example where a Lambda Expression is used:

    HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
    Random rand = new Random(47);
    int i=0;
    while(i<5){
        i++;
        int key = rand.nextInt(20);
        int value = rand.nextInt(50);
        System.out.println("Inserting key: "+key+" Value: "+value);
        Integer imap =hm.put(key,value);
        if( imap == null){
            System.out.println("Inserted");
        }
        else{
            System.out.println("Replaced with "+imap);
        }               
    }

    hm.forEach((k,v) -> System.out.println("key: "+k+" value:"+v));

Output:

Inserting key: 18 Value: 5
Inserted
Inserting key: 13 Value: 11
Inserted
Inserting key: 1 Value: 29
Inserted
Inserting key: 8 Value: 0
Inserted
Inserting key: 2 Value: 7
Inserted
key: 1 value:29
key: 18 value:5
key: 2 value:7
key: 8 value:0
key: 13 value:11

Also one can use Spliterator for the same.

Spliterator sit = hm.entrySet().spliterator();

UPDATE


Including documentation links to Oracle Docs. For more on Lambda go to this link and must read Aggregate Operations and for Spliterator go to this link.