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

Discussions

java - Iterate through a HashMap - Stack Overflow
Since all maps in Java implement the Map interface, the following techniques will work for any map implementation (HashMap, TreeMap, LinkedHashMap, Hashtable, etc.) Method #1: Iterating over entries using a For-Each loop. This is the most common method and is preferable in most cases. It should be used if you need both map keys ... More on stackoverflow.com
🌐 stackoverflow.com
loops - How to iterate through a Map in java? - Stack Overflow
Check out for more examples about iteration through maps in Java. More on stackoverflow.com
🌐 stackoverflow.com
How do I efficiently iterate over each entry in a Java Map?
What are the best practices for iterating over key-value pairs in a Java Map? In this guide, we'll explore different ways to traverse a Map efficiently usi... More on janbasktraining.com
🌐 janbasktraining.com
1
April 18, 2025
Is the iteration order of HashSet deterministic?
If you iterate over a hashmap, and then iterate over it again, you will get the same order. If you clone into a different hashmap, you will get a different order, and if you rerun the program, you'll get yet another order. Additionally, inserting new elements and removing old elements also will change the iteration order arbitrarily. If all you do is immutable operations to one map in one invocation of the program, though, iteration order is stable. More on reddit.com
🌐 r/rust
22
23
January 6, 2021
🌐
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. It provides a short and readable way to process key-value pairs.
🌐
Medium
medium.com › javarevisited › iterating-over-maps-is-an-important-topic-when-it-comes-to-working-with-maps-in-java-549deacdeaf9
Iterating over maps is an important topic when it comes to working with maps in Java.
October 10, 2023 - There are three main ways to iterate over a map in Java: Iterating over keys: In this method, we obtain the set of keys from the map using the keySet() method and iterate over the set using a for-each loop or an iterator.
🌐
Techie Delight
techiedelight.com › home › java › iterate map in java using keyset() method
Iterate Map in Java using keySet() method | Techie Delight
July 7, 2026 - Since the map doesn’t extend the Collection interface, it doesn’t have its own iterator. Since Set extends the Collection interface, we can get an iterator to set of keys returned by keySet().
🌐
Squash
squash.io › how-to-iterate-over-entries-in-a-java-map
How To Iterate Over Entries In A Java Map - Squash Labs
November 24, 2023 - For each key, we retrieve the corresponding value using the get() method of the map. Finally, we print the key-value pair. The question of how to iterate over entries in a Java Map is commonly asked by Java developers who need to process or manipulate the data stored in a map.
Find elsewhere
🌐
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 - One of the most efficient ways to iterate over a Java Map is by utilizing the entrySet() method combined with a for-each loop. This method allows you to traverse both keys and values simultaneously.
Top answer
1 of 3
52

For basic utilisation, the HashMap is the best, I've put how to iterate over it, easier than using an iterator :

public static void main (String[] args) {
    //a map with key type : String, value type : String
    Map<String,String> mp = new HashMap<String,String>();
    mp.put("John","Math");    mp.put("Jack","Math");    map.put("Jeff","History");

    //3 differents ways to iterate over the map
    for (String key : mp.keySet()){
        //iterate over keys
        System.out.println(key+" "+mp.get(key));
    }

    for (String value : mp.values()){
        //iterate over values
        System.out.println(value);
    }

    for (Entry<String,String> pair : mp.entrySet()){
        //iterate over the pairs
        System.out.println(pair.getKey()+" "+pair.getValue());
    }
}

A quick explanation :

for (String name : mp.keySet()){
        //Do Something
}

means : "For all string from the keys of the map, we'll do something, and at each iteration we will call the key 'name' (it can be whatever you want, it's a variable)


Here we go :

public String[] getAllKeys(){ 
    int i = 0;
    String allkeys[] = new String[buckets.length];
    KeyValue val = buckets[i];

    //Look at the first one          
    if(val != null) {             
        allkeys[i] = val.key; 
        i++;
    }

    //Iterate until there is no next
    while(val.next != null){
        allkeys[i] = val.next.key;
        val = val.next;
        i++;
    }

    return allkeys;
}
2 of 3
3

See if this helps,

  HashMap< String, String> map = new HashMap<>();
  Set<String> keySet = map.keySet();
  Iterator<String> iterator = keySet.iterator();
  while(iterator.hasNext())
  {
    //iterate over keys
  }

//or iterate over entryset 
Iterator<Entry<String, String>> iterator2 = map.entrySet().iterator();

while(iterator2.hasNext())
{
    Entry<String, String> next = iterator2.next();
    //get key
    next.getKey();
    //get value
    next.getValue();
}
🌐
DevQA
devqa.io › 4-different-ways-iterate-map-java
Different Ways to Iterate Through a Map in Java
Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (Integer key : map.keySet()) { System.out.println("Key = " + key); } for (Integer value : map.values()) { System.out.println("Value = " + value); } ... Map<Integer, Integer> map ...
🌐
LabEx
labex.io › tutorials › java-how-to-loop-through-java-map-keys-425177
How to loop through Java Map keys | LabEx
Map<String, Integer> data = new HashMap<>(); try { data.keySet().forEach(key -> { try { // Potential risky operation processKey(key, data.get(key)); } catch (Exception e) { // Handle individual key processing errors System.err.println("Error processing key: " + key); } }); } catch (Exception e) { // Global error handling System.err.println("Iteration failed"); } RUN · Use appropriate iteration method based on use case ... At LabEx, we emphasize understanding these practical techniques to write robust and efficient Java code. By exploring different methods of looping through Java Map keys, developers can select the most appropriate approach based on their specific programming requirements.
🌐
ConcretePage
concretepage.com › java › how-iterate-map-java
How to Iterate Map in Java
January 31, 2022 - Iterate over keys. for (Integer key : map.keySet()) { System.out.println(key + " " + map.get(key)); } Map.values
🌐
Programiz
programiz.com › java-programming › examples › iterate-over-hashmap
Java Program to Iterate over a HashMap
import java.util.HashMap; import java.util.Map.Entry; class Main { public static void main(String[] args) { // Creating a HashMap HashMap<String, String> languages = new HashMap<>(); languages.put("Java", "Enterprise"); languages.put("Python", "ML/AI"); languages.put("JavaScript", "Frontend"); System.out.println("HashMap: " + languages); // iterating through key/value mappings System.out.print("Entries: "); for(Entry<String, String> entry: languages.entrySet()) { System.out.print(entry); System.out.print(", "); } // iterating through keys System.out.print("\nKeys: "); for(String key: languages.keySet()) { System.out.print(key); System.out.print(", "); } // iterating through values System.out.print("\nValues: "); for(String value: languages.values()) { System.out.print(value); System.out.print(", "); } } }
🌐
EDUCBA
educba.com › home › software development › software development tutorials › java tutorial › java iterate map
Java Iterate Map | Learn How does Iteration Works in Map?
July 1, 2023 - Based on the requirement, we can iterate the map in any of the above ways. ... import java.util.HashMap; import java.util.Map; public class ForEachMapIteration { public static void main(String[] args) { // creating a hashmap object Map<Integer, String> names = new HashMap<>(); // adding key and values to hash map names.put(1, "Paramesh"); names.put(2, "Amardeep"); names.put(3, "Venkatesh"); names.put(4, "Ramesh"); names.put(5, "Suresh"); names.put(3, "Krishna"); names.put(4, "Rama"); names.put(5, "Rajitha"); // iterating key and value with forEach loop names.forEach((key, value) -> { System.out.println("ID =>" + key + " Name => " + value); }); } }
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Medium
medium.com › @reetesh043 › mastering-map-iteration-in-java-a-comprehensive-guide-f64f12115d36
How To Iterate Map in Java. Introduction | by Reetesh Kumar | Medium
January 25, 2024 - With Java 8 and later, we can use streams to iterate through maps elegantly. // Method 3: Using Java Streams System.out.println("Method 3: Using Java Streams"); userMap.forEach((username, user) -> { System.out.println("Username: " + username + ", User: " + user); }); We can also iterate through keys or values separately.
🌐
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.
🌐
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 - Map<Integer, String> colors = new TreeMap<>(); colors.put(1, "Red"); colors.put(2, "Green"); colors.put(3, "Blue"); colors.forEach((key, value) -> System.out.println("Color code: " + key + ", Color name: " + value)); ... Provides a clean and concise syntax for iterating through entries. Fits well with lambda expressions. ... When you want a shorter and more modern syntax for iterating through Map entries. Suitable for Java 8+ projects looking for improved code readability.
🌐
W3Schools
w3schools.com › java › java_howto_loop_through_hashmap.asp
Java How To Loop Through a HashMap
close() delimiter() findInLine() ... Java Server Java Syllabus Java Study Plan Java Interview Q&A ... Loop through the items of a HashMap with a for-each loop....
🌐
JanBask Training
janbasktraining.com › community › java › how do i efficiently iterate over each entry in a java map?
How do I efficiently iterate over each entry in a Java Map? | JanBask Training Community
April 18, 2025 - Cons: Slower due to repeated get() calls. In conclusion, the best way to iterate over a Java Map depends on the use case. If you need both keys and values, entrySet() is the most efficient.
🌐
Javatutorial
javatutorial.net › java-iterate-hashmap-example
Java Iterate through a HashMap Example | Java Tutorial Network
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; public class IterateHashMap { public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); map.put("key1", "value1"); map.put("key2", "value2"); Iterator<Entry<String, String>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> pair = (Map.Entry<String, String>) it.next(); System.out.println(pair.getKey() + " = " + pair.getValue()); } } }