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());
}
Answer from ScArcher2 on Stack Overflow
Top answer
1 of 16
5966
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.

🌐
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 - We create a MapIterator object, which is part of Apache Commons Collections, and pass the IterableMap object to it. We then invoke the mapIterator() method on the IterableMap object to obtain a MapIterator type.
Discussions

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
Iterate through hashmap using the classic for-loop
I suppose you could fetch the iterator of the entry set of the hashmap, and use that, but that seems a bit silly and basically ignores the index anyway. The reason you haven't found any examples is because a tradional for loop is mostly used when you need the index, but a HashMap isn't ordered so the index is meaningless. Iterator> iterator = myHashMap.entrySet().iterator(); for (;iterator.hasNext();) { Map.Entry myEntry = iterator.next(); } or even Iterator> iterator = myHashMap.entrySet().iterator(); int size = myHashMap.size(); for (int i = 0; i < size; i++) { Map.Entry myEntry = iterator.next(); } Though I really wouldn't use the last one. Using iterator.next() without first checking iterator.hasNext() is not really the correct way to use an iterator. More on reddit.com
🌐 r/javahelp
6
1
January 18, 2022
Unable to iterate through HashMap in Java using forEach and entrySet().
Maybe you don't understand how the hash map works. A key is always unique. In the test case,  which seems to be: 0 1 2 0       3 4 5 2       1 3 1 5 You first add the first element to hashmap, key: 0 and value: 0. Then you iterate and find the another zero on the first row. Now you add to hashmap, key: 0, value: 3. You are using the i-coordinate as the key. Of course in this example there are two 0's on the same row. Only one of these can be saved on the hash map. I have no idea how the hashmap would be of any use in this problem anyway. You want to store coordinates, right? Can you not create a class Point or something and store them on a list? More on reddit.com
🌐 r/learnjava
4
4
January 23, 2025
How to get the "index" of a given key in a HashMap Java
I might be wrong. I think Hashmap is not an ordered list, so you dont have indexes, you have keys. Even if you iterate through the same hashmap, probably you could see that dont return the values always in the same order, or at least, you cant trust that are going to be return in the order you had insert them. You can use the method containsKey to find if that key exist. More on reddit.com
🌐 r/learnjava
15
4
November 5, 2021
People also ask

What is the difference between Iterator and Enumeration in Java?
There are three significant differences between iterators and enumeration: In Enumerator, we can not add/remove elements from a collection, Although, In Iterators, we can remove elements from the underlying collection in the iteration using its inbuilt remove() method.Availability: An Iterator is available in all modern collection classes. An enumerator is available in legacy classes, i.e., Vector/Stack, etc. Iterator has more improved method names than Enumerator. For example, In Enumerator, there is a methodhasMoreElement(),which becomeshasNext()in the Iterator.
🌐
interviewkickstart.com
interviewkickstart.com › home › blogs › learn › how to iterate a map in java
How to Iterate a Map in Java | Interview Kickstart
In Java, why is the collection interface not extended by the Map interface?
Mainly because they are incompatible, the collection has a methodadd(Object o). The Map cannot have such a method because it needs a key-value pair. Also, there are other reasons like Map supportskeySet, valueSet. Collection classes do not have such methods. Due to such significant differences, the Map interface does not use a collection interface.
🌐
interviewkickstart.com
interviewkickstart.com › home › blogs › learn › how to iterate a map in java
How to Iterate a Map in Java | Interview Kickstart
🌐
GeeksforGeeks
geeksforgeeks.org › java › iterate-map-java
How to Iterate Any Map in Java? - GeeksforGeeks
September 1, 2026 - Java 8 introduced the forEach() method, which allows us to iterate over a map using a lambda expression.
🌐
CodeGym
codegym.cc › java blog › java collections › how to iterate a map in java
How to iterate a Map in Java
January 8, 2025 - User the iterator if you have to modify the map. Use the for-each loop if you have nested loops (to avoid complexity). The Stream API, introduced in Java 8, offers a functional and concise way to iterate over a Map.
🌐
Interview Kickstart
interviewkickstart.com › home › blogs › learn › how to iterate a map in java
How to Iterate a Map in Java | Interview Kickstart
March 29, 2026 - Java iterate map is a method of parsing through all key-value pairs in a database or page so that they can be modified and processed. Iterating a map in Java is done to access and display controls, apply conditional logic and checks, update entries, for data analysis and transformation, and for data integrity and debugging.
Find elsewhere
🌐
Sentry
sentry.io › sentry answers › java › how to iterate over a hashmap in java
Iterate Over a HashMap in Java with Three Methods | Sentry
2 weeks ago - Perhaps the most straightforward approach to iterating over a HashMap is to use a for-each loop to iterate over each entry. Using the HashMap.entrySet() will return a set view of the mappings or entries in the HashMap. import java.util.HashMap; ...
🌐
ProsperaSoft
prosperasoft.com › home › blogs › full-stack › backend › java › iterate java map
How do I efficiently iterate over each entry in a Java Map? - ProsperaSoft blogs
May 29, 2025 - With the introduction of Java 8, the Stream API provides a powerful way to iterate over collections, including Maps. The Stream API facilitates a more functional approach to programming, allowing for elegant operations on your data.
🌐
Academic Help
academichelp.net › coding › java › how-to-iterate-map.html
How to Iterate Map in Java: Mastering Efficient Map Iteration
December 26, 2023 - Method 2 is a more efficient approach as it allows us to access both the key and value in a single iteration. It is recommended when we need to perform operations that involve both the keys and the values of the map. Java 8 introduced the forEach method for collections, including maps.
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Exploring Different Techniques to Iterate a List of Maps in Java - Java Code Geeks
July 1, 2024 - Inside a lambda, we access the key and value from each Map.Entry. ... Java 8 also introduced the forEach method, which can be used with lambda expressions to iterate over collections.
🌐
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.Iterator; import java.util.Map; public class LoopMap4 { 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 -> Set -> Iterator -> Map.Entry Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<Integer, String> entry = iterator.next(); System.out.println("Key : " + entry.getKey() + " Value :" + entry.getValue()); } } } This method involves iterating over the key set an
🌐
DevQA
devqa.io › java-iterate-list-of-maps
How to Iterate a List of Maps in Java
August 2, 2023 - You can then iterate through this set, and for each key, fetch the corresponding value using the get() method. for (Map<String, Object> map : listOfMaps) { for (String key : map.keySet()) { Object value = map.get(key); System.out.format("%s: ...
🌐
DevQA
devqa.io › 4-different-ways-iterate-map-java
Different Ways to Iterate Through a Map in Java
November 10, 2019 - Map map = new HashMap(); Iterator entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); Integer key = (Integer)entry.getKey(); Integer value = (Integer)entry.getValue(); System.out.pr...
🌐
Edureka
edureka.co › blog › iterate-maps-java
How to Iterate Maps in Java | 5 Different Ways to Iterate Map | Edureka
June 17, 2021 - The Java Map interface, java.util.Map, represents the mapping between a key and a value i.e. a Java Map can store pairs of keys and values where each key is linked to a specific value. Once stored in a Map, you can later look up a particular value by using just the key of assigned to that value. Each key can be mapped to at most one value. We cannot iterate a Map directly using iterators, because Map is not Collection so we use some other ways to iterate Maps which are described in detail further in this blog.
🌐
Javatpoint
javatpoint.com › how-to-iterate-map-in-java
How to iterate Map in Java - Javatpoint
How to iterate Map in Java with oops, string, exceptions, multithreading, collections, jdbc, rmi, fundamentals, programs, swing, javafx, io streams, networking, sockets, classes, objects etc,
🌐
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 - When you want a shorter and more modern syntax for iterating through Map entries. Suitable for Java 8+ projects looking for improved code readability. ... You can use an Iterator in conjunction with the entrySet() method to navigate through a Map.
🌐
SourceBae
sourcebae.com › home › how do i efficiently iterate over each entry in a java map?
How do I efficiently iterate over each entry in a Java Map? - SourceBae
August 21, 2025 - The entrySet iterator can sometimes ... iterations. Another widely popular technique for iterating over a Java Map is using the keySet() method....
🌐
Scientech Easy
scientecheasy.com › home › blog › how to iterate map in java
How to Iterate Map in Java - Scientech Easy
May 16, 2025 - Note that we cannot iterate over a map directly using iterator because Map interface is not the part of the Collection interface. To iterate map using iterator, you must familiar with Map.Entry<K, V> interface. Since all maps in Java implement Map interface, this technique can be used with ...
🌐
freeCodeCamp
freecodecamp.org › news › java-iterator-hashmap-how-to-iterate-through-a-hashmap-with-a-loop
Java Iterator Hashmap – How to Iterate Through a Hashmap With a Loop
May 5, 2023 - Firstly, you initiate the hashmap, use an iterator to iterate through the hashmap, and finally display your output. One of the simplest ways to iterate through a hashmap is by using a for-each loop.
🌐
xperti
xperti.io › home › how to iterate over a map in java
How To Iterate Over a Map In Java
May 9, 2022 - The iterator is an interface used to iterate over a collection. As we can view maps as a collection, they can also be iterated via the iterator. The iterator interface is also an alternate for Enumeration in Java Collections Framework.