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
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!

🌐
Medium
medium.com › @AlexanderObregon › javas-map-foreach-method-explained-0fe0dc60fa5e
Java's Map.forEach() Method Explained
December 7, 2024 - The forEach() method in the java.util.Map class was introduced in Java 8 and provides a straightforward way to process entries in a map. It applies a specified action to each key-value pair, allowing you to work with the data in a functional ...
Discussions

What is the difference between map and forEach in Java streams in this case?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnjava
12
2
June 2, 2024
Is java8 foreach on a map thread safe?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
6
3
September 23, 2021
Why does the List interface have forEach, but not map?
why isn't every List a Stream? To answer this part of the question, it's because a stream is a fundamentally different datatype than a list. A list represents a collection of data, while a stream represents a pipeline for processing data. Streams can only be processed once, and are designed to perform multiple operations on some provided data. They don't store any intermediate results, and then do lazy processing once you specify a terminal operator (like toList() or forEach()). For example, if you had something like this: Stream a = List.of(1, 2, 3).stream(); Stream b = a.filter(n -> n > 1); Stream c = b.map(n -> String.valueOf(n)); List d = c.toList(); This is functionally identical to this: List d = List.of(1, 2, 3).stream() .filter(n -> n > 1) .map(n -> String.valueOf(n)) .toList(); If you inspected b, however, it would not contain any data about what elements were remaining, because the stream has not executed yet. Assigning the various steps of the stream along the way doesn't actually DO anything to the data, it just creates pointers to instances of the pipeline. As mentioned before, the pipeline can only be executed once, which means a stream is consumed when you perform a terminal operation on it. It also can't be executed if you chain it to another pipeline. If, in the example above, you tried to do b.toList(), you'd get an IllegalStateException, because b was already operated on. If you did c.toList(), you'd get a list of "2", "3". If you did c.toList() a second time, you'd once again get an IllegalStateExcecution, because c has already been consumed. The intermediate operators like map actually do nothing except modify the pipeline definition until you call toList at the end. Once you execute toList, then the pipeline operates in a lazy way, evaluating the data elements one at a time. So, to recap: List: collection of ordered data Stream: an operation pipeline definition More on reddit.com
🌐 r/java
90
121
October 26, 2024
How To Iterate Over Hashmap In A For-Loop Context?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnjava
8
1
July 20, 2023
🌐
Mkyong
mkyong.com › home › java8 › java 8 foreach examples
Java 8 forEach examples | mkyong.com
December 4, 2020 - public static void loopMapClassic() ... + ", Value : " + entry.getValue()); } } 1.2 In Java 8, we can use forEach to loop a Map and print out its entries....
🌐
JetBrains
jetbrains.com › help › inspectopedia › Java8MapForEach.html
'Map.forEach()' can be used | Inspectopedia Documentation
June 30, 2026 - void print(Map<String, Integer> map) { map.entrySet().forEach(entry -> { String str = entry.getKey(); System.out.println(str + ":" + entry.getValue()); }); }
🌐
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.
🌐
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.
Find elsewhere
🌐
BeginnersBook
beginnersbook.com › 2017 › 10 › java-8-foreach
Java 8 forEach method with example
In Java 8, we have a newly introduced forEach method to iterate over collections and Streams in Java. 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.
🌐
Alvin Alexander
alvinalexander.com › java › java-8-how-to-iterate-elements-map-hashmap
How to iterate (loop) over the elements in a Map in Java 8 | alvinalexander.com
package java8_tests; import java.util.HashMap; import java.util.Map; public class IterateOverJava8Map { public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); map.put("first_name", "Alvin"); map.put("last_name", "Alexander"); // java 8 map.forEach((k,v)->System.out.println("key: " + k + ", value: " + v)); // prior to java 8 for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println("key: " + entry.getKey() + ", value: " + entry.getValue()); } } }
🌐
Medium
medium.com › @yadavsunil9699 › exploring-multiple-ways-to-iterate-through-maps-in-java-133441904b1e
Exploring Multiple Ways to Iterate Through Maps in Java | by Yadavsunil | Medium
September 8, 2023 - Java 8 introduced functional programming features, making it easier to work with Maps using Streams. Map<String, Double> prices = new HashMap<>(); prices.put("Apple", 1.99); prices.put("Banana", 0.99); prices.put("Orange", 1.49); prices.forEach((key, value) -> System.out.println("Item: " + key + ", Price: " + value));
🌐
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 - 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 - Since Java 8, the forEach() has been added in the following classes or interfaces: Iterable interface – This makes Iterable.forEach() method available to all collection classes except Map · Map interface – This makes forEach() operation available to all map classes.
🌐
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 ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › iterate-map-java
How to Iterate Any Map in Java? - GeeksforGeeks
September 1, 2026 - import java.util.*; public class ... the next entry. Java 8 introduced the forEach() method, which allows us to iterate over a map using a lambda expression....
🌐
Mkyong
mkyong.com › home › java › how to loop map in java
How to loop Map in Java | mkyong.com
March 13, 2024 - package com.mkyong.examples; import java.util.HashMap; import java.util.Map; public class LoopMap2 { public static void main(String[] args) { Map<Integer, String> map = new HashMap<>(); map.put(1, "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: " + id + ", Name: " + name); }); } } ... We can use stream() to loop, filtering and collect in Java 8.
🌐
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 ...
🌐
OneCompiler
onecompiler.com › java › 3uawkwmvq
Java Map Iteration using forEach and Java 8 Streams
This framework also defines map interfaces and several classes in addition to Collections.
🌐
Reddit
reddit.com › r/learnjava › what is the difference between map and foreach in java streams in this case?
r/learnjava on Reddit: What is the difference between map and forEach in Java streams in this case?
June 2, 2024 -

I know map is not a terminal operation, but could someone explain this in more detail?

userList.stream().map(i -> {
    System.out.println(i);
    return 0;
}).collect(Collectors.toList());
// VS
userList.forEach(System.out::println);
Top answer
1 of 4
3
If the code is exactly as presented, both are doing the same thing. There is a difference though, as the first stream creates a list of 0's the same size as the userList. There just isn't a variable to assign the created list to. List mappedUserList = userList.stream() .map(i -> { System.out.println(i); return 0; }) .collect(Collectors.toList()); This isn't possible with the second stream. To have the same functionality, the second stream would look like this: List mappedUserList = new ArrayList<>(); userList.stream().forEach(i -> { System.out.println(i); mappedUserList.add(i); });
2 of 4
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
Reddit
reddit.com › r/javahelp › is java8 foreach on a map thread safe?
r/javahelp on Reddit: Is java8 foreach on a map thread safe?
September 23, 2021 -

If I iterate using it.next() through a map and use a thread within the loop it doesn't work as expected. Is using the java8 foreach safe? I would have thought it were safe but I'm getting so extra loops in there I didn't expect eg

this.mymap.forEach(
      (k, v) -> {
    	  new Thread() {
    	    public void run() {
		Messages message = (Messages) v; //is this thread safe?

                //do http request to api
            }
          }.start();

});
Top answer
1 of 4
4
Unless you're using ConcurrentHashMap, all of the basic Java collections (HashMap, TreeMap, etc.) require external synchronization. HashMap in particular is vulnerable to rehash. If the HashMap capacity reaches the threshold, HashMap has to recreate the backing array, a power of two larger. If you put on one thread and that causes rehash, then without external synchronization, iteration on another thread can have unpredictable results. Classic race condition.
2 of 4
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.