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.
🌐
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
🌐
Javainsimpleway
javainsimpleway.com › hashmap-with-looping
HashMap with Looping | Javainsimpleway
We can iterate hashmap using enhanced for loop with keyset() method or by using enhanced for loop with EntrySet() method or by using iterator ... import java.util.*; public class HashMapEnhancedForLoopExample { public static void main(String args[]) { HashMap<Integer, String> hashMap = new ...
🌐
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.
🌐
Academic Help
academichelp.net › coding › java › how-to-iterate-map.html
How to Iterate Map in Java: Mastering Efficient Map Iteration
December 26, 2023 - Here’s how you can use the Enhanced for-loop to iterate through a Map: import java.util.HashMap; import java.util.Map; public class EnhancedForLoopMapIterationExample { public static void main(String[] args) { Map<String, Integer> scores = new HashMap<>(); scores.put("John", 95); scores.put("Alice", 87); scores.put("Bob", 78); // Using Enhanced for-loop for Map iteration for (Map.Entry<String, Integer> entry : scores.entrySet()) { String name = entry.getKey(); int score = entry.getValue(); System.out.println(name + " - " + score); } } } Yes, there is a difference between iterating over a Hashtable and a HashMap in Java.