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
🌐
W3Schools
w3schools.com › java › ref_hashmap_foreach.asp
Java HashMap forEach() Method
Java Data Structures Java Collections Java List Java ArrayList Java LinkedList Java List Sorting Java Set Java HashSet Java TreeSet Java LinkedHashSet Java Map Java HashMap Java TreeMap Java LinkedHashMap Java Iterator Java Algorithms · Java Wrapper Classes Java Generics Java Annotations Java RegEx Java Threads Java Lambda Java Advanced Sorting
🌐
Programiz
programiz.com › java-programming › library › hashmap › foreach
Java HashMap forEach()
the forEach() method performs the action specified by lambda expression for each entry of the hashmap · the lambda expression reduces each value by 10% and prints all the keys and reduced values · To learn more about lambda expression, visit Java Lambda Expressions.
🌐
Mkyong
mkyong.com › home › java8 › java 8 foreach examples
Java 8 forEach examples - Mkyong.com
December 4, 2020 - 1.2 In Java 8, we can use forEach to loop a Map and print out its entries. public static void loopMapJava8() { Map<String, Integer> map = new HashMap<>(); map.put("A", 10); map.put("B", 20); map.put("C", 30); map.put("D", 40); map.put("E", 50); ...
🌐
Medium
medium.com › @AlexanderObregon › javas-map-foreach-method-explained-0fe0dc60fa5e
Java’s Map.forEach() Method Explained | Medium
December 7, 2024 - import java.util.HashMap; import java.util.Map; public class LoggingExample { public static void main(String[] args) { Map<String, Integer> data = new HashMap<>(); data.put("User1", 200); data.put("User2", 300); data.put("User3", 150); data.forEach((user, score) -> System.out.println(user + " scored: " + score)); } } ... This example highlights the simplicity of using a lambda expression with forEach() to process and log data.
🌐
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 - So, when we use the forEach methosd we have specified in the lambda expression to convert the key into uppercase and the value multiplied by 10. In this way, we can use the forEach method in the Java ...
🌐
Sentry
sentry.io › sentry answers › java › how to iterate over a hashmap in java
How to Iterate Over a HashMap in Java | Sentry
In this approach, we make use of lambda expressions, which have been available in Java since version 8. A lambda expression operates on input parameters and returns a value. The lambda expression solution to this problem does not need each key-value ...
🌐
Makeseleniumeasy
makeseleniumeasy.com › 2023 › 03 › 24 › how-to-iterate-map-in-java-using-stream-and-lambda
How To Iterate Map In Java Using Stream and Lambda?
package collectionsExamples; import java.util.*; public class IterateMapUsingLambdaStreams { public static void main(String[] args) { //create a map data HashMap mapData = new HashMap<>(); mapData.put("id", "1"); mapData.put("name", "Amod"); mapData.put("address", "New York"); mapData.put("skills", "Java Selenium"); mapData.put("mob", "969768"); // Using forEach and lambda mapData.forEach((key, value) -> System.out.println("Key = " + key + " | Value = " + value)); // Using keyset(), forEach and lambda mapData.keySet().forEach((key) -> System.out.println("Key = " + key + " | Value = " + mapData
🌐
Vultr
docs.vultr.com › java › standard-library › java › util › HashMap › forEach
Java HashMap forEach() - Apply Function to Items | Vultr Docs
November 19, 2024 - The forEach() method in Java’s HashMap class provides a way to iterate through each entry in the map and execute a specific action. This method, introduced in Java 8, simplifies iterating over map entries, enhances readability, and reduces ...
Find elsewhere
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!

🌐
Educative
educative.io › answers › what-is-the-linkedhashmapforeach-method-in-java
What is the LinkedHashMap.forEach() method in Java?
You can read more about the LinkedHashMap class here. The forEach() method allows for an action to be performed on each entry of the LinkedHashMap object until all entries have been processed or an exception is thrown.
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-iterate-hashmap-in-java
How to Iterate HashMap in Java? - GeeksforGeeks
July 23, 2025 - // Iterating HashMap using Lambda Expressions- forEach() // Importing Map and HashMap classes // from java.util package import java.util.HashMap; import java.util.Map; // Class public class GFG { // Main driver method public static void main(String[] args) { // Creating hash map Map<Character, String> charType = new HashMap<Character, String>(); // Inserting elements(key-value pairs) // in the hash map ( Custom inputs) charType.put('A', "Apple"); charType.put('B', "Basketball"); charType.put('C', "Cat"); charType.put('D', "Dog"); // Iterating through forEach and // printing the elements charType.forEach( (key, value) -> System.out.println(key + " = " + value)); } }
🌐
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 - 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: Map<String, ...
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
300

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.

🌐
Java Guides
javaguides.net › 2019 › 06 › iterate-over-hashmap-java-using-lambda.html
Iterate Over a HashMap Using Lambda Expressions in Java
June 21, 2024 - The forEach method in HashMap allows you to iterate over the entries of the map using a BiConsumer. This method takes a lambda expression that defines the action to be performed for each entry.
🌐
BeginnersBook
beginnersbook.com › 2017 › 10 › java-8-foreach
Java 8 forEach method with example
In this guide, we will learn how to use forEach() and forEachOrdered() methods to loop a particular collection and stream. import java.util.Map; import java.util.HashMap; public class Example { public static void 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 each key and value pair * of HashMap.
🌐
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 - Let’s iterate through the MutableMap ... } In the code above, we invoke forEachKeyValue() on a MutableMap object to iterate through the Map and use a lambda expression to get the keys and values....
🌐
Java Guides
javaguides.net › 2024 › 06 › java-hashmap-foreach-method.html
Java HashMap forEach() Method
June 11, 2024 - The HashMap.forEach() method in Java provides a way to perform a specified action for each entry in the HashMap. Using lambda expressions with this method makes the code more concise and readable.
🌐
TutorialsPoint
tutorialspoint.com › how-can-we-iterate-the-elements-of-list-and-map-using-lambda-expression-in-java
How can we iterate the elements of List and Map using lambda expression in Java?
import java.util.*; public class ListIterateLambdaTest { public static void main(String[] argv) { List<String> countryNames = new ArrayList<String>(); countryNames.add("India"); countryNames.add("England"); countryNames.add("Australia"); countryNames.add("Newzealand"); countryNames.add("South Africa"); // Iterating country names through forEach using Lambda Expression countryNames.forEach(name -> System.out.println(name)); } } ... import java.util.*; public class MapIterateLambdaTest { public static void main(String[] args) { Map<String, Integer> ranks = new HashMap<String, Integer>(); ranks.put("India", 1); ranks.put("Australia", 2); ranks.put("England", 3); ranks.put("Newzealand", 4); ranks.put("South Africa", 5); // Iterating through forEach using Lambda Expression ranks.forEach((k,v) -> System.out.println("Team : " + k + ", Rank : " + v)); } }
🌐
Javabeginnerstutorial
javabeginnerstutorial.com › core-java-tutorial › java-8-lambda-foreach-map
Java 8 lambda foreach Map - Java Beginners Tutorial
February 12, 2016 - But now in this article i will show how to use Lambda expression to iterate Collection. class java_5_enhancedForLoop_Map { public static void main(String[] args) { Map<String, String> jbtObj = new HashMap<String, String>(); jbtObj.put("Website Name","Java Beginners Tutorial"); jbtObj.put("Language", "Java"); jbtObj.put("Topic", "Collection"); for (Map.Entry<String, String> entry : jbtObj.entrySet()) { System.out.println(entry.getKey() + " : "+ entry.getValue()); } // Iterating over collection object using iteration even before Java 5 Iterator<Entry<String, String>> iterator = jbtObj.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> thisEntry = (Entry<String, String>) iterator.next(); Object key = thisEntry.getKey(); Object value = thisEntry.getValue(); System.out.println(key+" : "+value); } } }