If you're only interested in the keys, you can iterate through the keySet() of the map:

Map<String, Object> map = ...;

for (String key : map.keySet()) {
    // ...
}

If you only need the values, use values():

for (Object value : map.values()) {
    // ...
}

Finally, if you want both the key and value, use entrySet():

for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    // ...
}

One caveat: if you want to remove items mid-iteration, you'll need to do so via an Iterator (see karim79's answer). However, changing item values is OK (see Map.Entry).

Answer from harto on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-iterate-hashmap-in-java
How to Iterate HashMap in Java? - GeeksforGeeks
July 23, 2025 - Iterating a HashMap through a for loop to use getValue() and getKey() functions. Implementation: In the code given below, entrySet() is used to return a set view of mapped elements.
Discussions

dictionary - Java : Iteration through a HashMap, which is more efficient? - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Given the following code, with two alternative ways to iterate through it, is there any performance difference between these two methods? Map map = new HashMap(); ... More on stackoverflow.com
🌐 stackoverflow.com
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
dictionary - How do I efficiently iterate over each entry in a Java Map? - Stack Overflow
If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map? Will the ordering of More on stackoverflow.com
🌐 stackoverflow.com
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
🌐
Sentry
sentry.io › sentry answers › java › how to iterate over a hashmap in java
How to Iterate Over a HashMap in Java | Sentry
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; ...
🌐
How to do in Java
howtodoinjava.com › home › collections framework › java hashmap › iterate over a hashmap: performance comparison
Iterate over a HashMap: Performance Comparison
July 27, 2023 - Map<String, Integer> map = new HashMap(); for (int i = 0; i < 10_00_000; i++) { map.put(String.valueOf(i), i); } We will iterate over the map in all four ways. We will also fetch the key and value from the map for all entries in the best suitable way.
Top answer
1 of 7
67

Your second option is definitely more efficient since you are doing a lookup only once compared to n number of times in the first option.

But, nothing sticks better than trying it out when you can. So here goes -

(Not perfect but good enough to verify assumptions and on my machine anyway)

public static void main(String args[]) {

    Map<String, Integer> map = new HashMap<String, Integer>();
    // populate map

    int mapSize = 500000;
    int strLength = 5;
    for(int i=0;i<mapSize;i++)
        map.put(RandomStringUtils.random(strLength), RandomUtils.nextInt());
    
    long start = System.currentTimeMillis();
    // alt. #1
    for (String key : map.keySet()) {
        Integer value = map.get(key);
        // use key and value
    }
    System.out.println("Alt #1 took "+(System.currentTimeMillis()-start)+" ms");
    
    start = System.currentTimeMillis();
    // alt. #2
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        String key = entry.getKey();
        Integer value = entry.getValue();
        // use key and value
    }
    System.out.println("Alt #2 took "+(System.currentTimeMillis()-start)+" ms");
}

RESULTS (Some interesting ones)

With int mapSize = 5000; int strLength = 5;
Alt #1 took 26 ms
Alt #2 took 20 ms

With int mapSize = 50000; int strLength = 5;
Alt #1 took 32 ms
Alt #2 took 20 ms

With int mapSize = 50000; int strLength = 50;
Alt #1 took 22 ms
Alt #2 took 21 ms

With int mapSize = 50000; int strLength = 500;
Alt #1 took 28 ms
Alt #2 took 23 ms

With int mapSize = 500000; int strLength = 5;
Alt #1 took 92 ms
Alt #2 took 57 ms

...and so on

2 of 7
11

The second snippet will be slightly faster, since it doesn't need to re-look-up the keys.

All HashMap iterators call the nextEntry method, which returns an Entry<K,V>.

Your first snippet discards the value from the entry (in KeyIterator), then looks it up again in the dictionary.

Your second snippet uses the key and value directly (from EntryIterator)

(Both keySet() and entrySet() are cheap calls)

🌐
Reddit
reddit.com › r/javahelp › iterate through hashmap using the classic for-loop
r/javahelp on Reddit: Iterate through hashmap using the classic for-loop
January 18, 2022 -

Hello!

Is it possible to iterate through a hashmap using the classic for-loop instead of for-each?

for (statement 1; statement 2; statement 3) {
  // code block to be executed
}

Looking online, i've seen a bunch of methods to iterate through a hashmap that are indeed more efficient, but i've never seen the classic for-loop ever used. Just wondering if this is possible or not, as i've never seen an example so far.

Thanks!

Top answer
1 of 3
3
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.
2 of 3
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.
🌐
Vultr Docs
docs.vultr.com › java › examples › iterate-over-a-hashmap
Java Program to Iterate over a HashMap | Vultr Docs
November 26, 2024 - Take advantage of Java 8's lambda expressions to succinctly iterate over a HashMap. Use the forEach method introduced in Java 8. ... Lambda expressions provide a clear and concise way to iterate over HashMap entries.
Find elsewhere
🌐
Hero Vired
herovired.com › learning-hub › topics › how-to-iterate-hashmap-in-java
Learn How to Iterate HashMap in Java
October 21, 2024 - There are several ways to iterate through a HashMap. Iterate through a HashMap EntrySet using iterators ... In the HashMap using a for loop in Java, you typically use the entrySet() method, which provides a set of key-value pairs.
🌐
Java67
java67.com › 2013 › 08 › best-way-to-iterate-over-each-entry-in.html
How to Iterate over HashMap in Java? Map.entrySet().iterator() Example | Java67
For example, if you just want to iterate over each entry of HashMap, without modifying Map, then iterating over entry set using Java 1.5 foreach loop seems the most elegant solution to me.
🌐
Programiz
programiz.com › java-programming › examples › iterate-over-hashmap
Java Program to Iterate over a HashMap
HashMap: {Java=Enterprise, JavaScript=Frontend, Python=ML/AI} Entries: Java=Enterprise, JavaScript=Frontend, Python=ML/AI, Keys: Java, JavaScript, Python, Values: Enterprise, Frontend, ML/AI, In the above example, we have created a hashmap named languages. Here, we have used the forEach loop to ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › traverse-through-a-hashmap-in-java
Traverse Through a HashMap in Java - GeeksforGeeks
forEach() is a method of HashMap that is introduced in java 8. It is used to iterate through the hashmap and also reduces the number of lines of code as proposed below as follows:
Published   July 11, 2025
🌐
GeeksforGeeks
geeksforgeeks.org › java › iterate-map-java
How to Iterate Any Map in Java? - GeeksforGeeks
July 23, 2025 - // Java program to demonstrate iteration over // Map.entrySet() entries using for-each loop import java.util.Map; import java.util.HashMap; class Geeks { public static void main(String[] arg) { Map<String,String> m = new HashMap<String,String>(); ...
🌐
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 - We then use a for-each loop to ... print them to the console. Another way to iterate through a hashmap is by using a while loop with an Iterator....
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
1633

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.

🌐
Reddit
reddit.com › r/learnjava › how to iterate over hashmap in a for-loop context?
r/learnjava on Reddit: How To Iterate Over Hashmap In A For-Loop Context?
July 20, 2023 -

I have a hashmap where each set's key is an Integer and the value is a custom inner class called node.

My for loop currently looks like this (hm is the variable that holds the hashmap):

for(int x=0; x<hm.entrySet().size(); x++){

    HashMap.Entry<Integer, node> currSet = hm.entrySet();
}

I know I need to do something to the " hm.entrySet() " inside the for-loop in order to access the set which is at index x. How do I do that?

Ideally I would have liked " hm.entrySet().get(x) " (the same syntax as accessing an arraylist) but that doesn't work.

What is the equivalent of " get(x) " in a situation like this?

🌐
Blogger
javarevisited.blogspot.com › 2011 › 12 › how-to-traverse-or-loop-hashmap-in-java.html
4 Example to Iterate over Map, HashMap, Hashtable or TreeMap in Java
August 19, 2022 - You can choose the way you want but if you want to access both keys and values then iterating using entrySet() is the best and fastest way as you don't need to call the get() method again to retrieve the value.
🌐
SourceBae
sourcebae.com › home › how to iterate over a hashmap in java
How to Iterate Over a HashMap in Java - SourceBae
August 21, 2025 - Discover the most efficient ways to iterate over a HashMap in Java using keySet, entrySet, and for Each. Learn expert tips to optimize code.
🌐
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 - The parallelStream() from the Stream API shows the best average performance for this larger map size. However, a parallel stream can introduce some overhead that might not benefit small operations. In this article, we focused on a critical but straightforward operation: iterating through the entries of a Map. We explored a couple of methods that can only be used with Java 8+, namely Lambda expressions and the Stream API.
🌐
TutorialsPoint
tutorialspoint.com › how-to-iterate-hashmap-in-java
How to Iterate HashMap in Java?
October 18, 2023 - Subsequently, we iterate via the HashMap the usage of the entrySet() method in a for loop · Step 1 Import the required Java utility classes.