You can iterate over the keys, entries or values.

for (String key : map.keySet()) {
    String value = map.get(key);
}

for (String value : map.values()) {
}

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

This is assuming your map has String keys and String values.

Answer from Eran on Stack Overflow
๐ŸŒ
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?

๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ java_howto_loop_through_hashmap.asp
Java How To Loop Through a HashMap
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Server Java Syllabus Java Study Plan Java Interview Q&A Java Certificate ... Loop through the items of a HashMap with a for-each loop.
๐ŸŒ
Javainsimpleway
javainsimpleway.com โ€บ hashmap-with-looping
HashMap with Looping | Javainsimpleway
Output Value of 1 is: One Value of 2 is: Two Value of 3 is: Three In this program, we have accessed all the keys of HashMap using keySet() method and then iterated all the keys using enhanced for loop and accessed value by passing key in each iteration in the loop. ... import java.util.*; public class HashMapEnhancedForLoopEntrySetExample { public static void main(String args[]) { HashMap<Integer, String> hashMap = new HashMap<Integer, String>(); hashMap.put(1, "One"); hashMap.put(2, "Two"); hashMap.put(3, "Three"); for (Map.Entry<Integer, String> entry : hashMap.entrySet()) { Integer key = entry.getKey(); Object value = entry.getValue(); System.out.println("Value of "+key+" is: "+value); } } }
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ traverse-through-a-hashmap-in-java
Traverse Through a HashMap in Java - GeeksforGeeks
HashMap class implements Map interface which allows us to store key. hashMap is a part of the java collections framework been up since Java 1.2. It internally uses hashing technique which is pretty fast. Syntax: public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Clonnable, Serial ยท We can iterate over mapping that is key and value pairs a was listed below that are later described as follows: Methods: Using an Iterator ยท Using enhanced for Loop (for-each loop) Using forEach() Method ยท
Published ย  July 11, 2025
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 723835 โ€บ certification โ€บ iterate-Map-enhanced-loop
it is possible to iterate Map by using enhanced loop? (Associate Certification (OCAJP 8) forum at Coderanch)
December 11, 2019 - 1. It can iterate over an array or a Collection but not a Map. 2. Using an enhanced for loop prevents the code from going into an infinite loop. 3. Using an enhanced for loop on an array may cause infinite loop. 4. An enhanced for loop can iterate over a Map.
๐ŸŒ
ZetCode
zetcode.com โ€บ java โ€บ hashmapiterate
Java HashMap iteration - learn how to iterate HashMap in Java
Enhanced for loop can be used to iterate over a HashMap. ... package com.zetcode; import java.util.HashMap; import java.util.Map; public class HashMapEnhancedFor { public static void main(String[] args) { HashMap<String, Integer> items = new HashMap(); items.put("coins", 5); items.put("pens", ...
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ how-to-iterate-hashmap-in-java
How to Iterate HashMap in Java? - GeeksforGeeks
July 23, 2025 - Next forEach method, which iterates the input objects that are in the entrySet(). See the below code. ... // Java Program to Iterate over HashMap // Loop through a HashMap using Stream API // Importing classes from // package named 'java.util' import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; // HashMap class public class GFG { // Main driver method public static void main(String[] arguments) { // Creating hash map Map<Integer, String> intType = new HashMap<Integer, String>(); // Inserting data(key-value pairs) in HashMap // Custom inputs intType.put(1, "First"); intType.put(2, "Second"); intType.put(3, "Third"); intType.put(4, "Fourth"); // Iterating every set of entry in the HashMap, and // printing all elements of it intType.entrySet().stream().forEach( input -> System.out.println(input.getKey() + " : " + input.getValue())); } }
๐ŸŒ
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 - In this example, we again create a new hashmap and add some key-value pairs to it. We then use a for loop with the keySet() method to iterate through the hashmap, retrieving each key and using it to get the corresponding value from the hashmap.
๐ŸŒ
Java67
java67.com โ€บ 2014 โ€บ 05 โ€บ 3-examples-to-loop-map-in-java-foreach.html
3 Examples to Loop Map in Java - Foreach vs Iterator | Java67
How do you sort a Map on keys and values in Java? (answer) ... While looping over Map you must remember that Map doesn't guarnatee any order, except TreeMap which guaranteeds sorting order and LinkedHashMap which keeps entries in the order they were inserted into Map. Other than that no Map guarantee any order, not even HashMap. For simple read only iteration the techniques you mentioned is sufficient, especially the one which gets entrySet() and then loop over Map using foreach loop.
๐ŸŒ
CodeGym
codegym.cc โ€บ java blog โ€บ java collections โ€บ enhanced for loop in java
Enhanced for loop in Java
February 13, 2025 - In conclusion, the Enhanced for loop in Java provides a simpler, safer, and more concise way to iterate over arrays and collections. It's a great feature that was introduced in Java 5, and it's something every Java developer should be familiar with.
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ how to iterate any map in java
How to Iterate Any Map in Java - Scaler Topics
March 14, 2024 - For entrySet(), we'll use an enhanced-for loop in this manner: Imagine a scenario where we just have to fetch the names of prisoners. It can be done by using keySet() in maps. Otherwise, we can use values() to fetch the list of all values: ... If it is the collections in Java weโ€™re discussing, the knowledge of Iterator is of utmost importance.
๐ŸŒ
Quora
quora.com โ€บ How-do-I-iterate-through-a-hashmap-using-a-loop-in-Java
How to iterate through a hashmap using a loop in Java - Quora
Oracle Certified Java Programmer, ... to get through all the items is using the foreach structure. HashMap<Integer,String> myHashMap = new HashMap<Integer,String>();...
๐ŸŒ
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 - I think java 5 way of looping hashmap using new for loop is best in terms of cleanliness and readability but Iterator provides in own advantage. as you can remove elements while looping or iterating over hashmap. ... Anonymous said... How to loop through map - use forloop or enhanced for loop.
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ java โ€บ how to iterate over a hashmap in java
How to Iterate Over a HashMap in Java | Sentry
import java.util.HashMap; import java.util.Map; public class Example { public static void main(String[] args) { Map<String, String> myMap = new HashMap<>() {{ put("a", "b"); put("c", "d"); }}; iterateUsingForEach(myMap); } public static void iterateUsingForEach(Map<String, String> map) { for (Map.Entry<String, String> entry : map.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); System.out.println("Key=" + key + ", Value=" + value); } } } This next approach uses the same for-each syntax as before, but this time we can make use of an Iterator.
๐ŸŒ
Medium
medium.com โ€บ @AlexanderObregon โ€บ javas-map-entryset-method-explained-1526a8cd58fb
Javaโ€™s Map.entrySet() Method Explained | Medium
December 15, 2024 - The entrySet() method pairs well with Java's enhanced for loop, making it a common choice for developers working with maps. Each element of the returned Set is a Map.Entry object, which provides methods to access the key and value directly. ... import java.util.HashMap; import java.util.Map; public class IterationExample { public static void main(String[] args) { Map<String, Double> itemWeights = new HashMap<>(); itemWeights.put("Laptop", 2.5); itemWeights.put("Tablet", 0.7); itemWeights.put("Phone", 0.2); System.out.println("Item Weights (in kg):"); for (Map.Entry<String, Double> entry : itemWeights.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue() + " kg"); } } }
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-iterate-a-hashmap-in-java
How to iterate a HashMap in Java
There are several ways to iterate a HashMap in Java. However, the three listed below are the most common. ... In the code below, hash_map.entrySet() is used to return a set view of the mapped elements. Now, getValue() and getKey() functions, key-value pairs can be iterated. ... In the code below, the forEach function is used to iterate the key-value pairs.
๐ŸŒ
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 are iterating through keys, values, and key/value mappings of the hash map. We have used the iterator() method to iterate over the hashmap. Here, hasNext() - returns true if there is next element in the hashmap ... Note: We can also use the HashMap forEach() method to iterate over the hashmap.