Home > DeveloperSection > Forums > Iterate through a HashMap
jayprakash sharma
jayprakash sharma

Total Post:117

Points:821
Posted on    May-04-2015 12:07 AM

 Java Java 
Ratings:


 1 Reply(s)
 596  View(s)
Rate this:
What's the best way to iterate over the items in a HashMap?


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Supported
Posted on    May-04-2015 12:41 AM

Iterate through the entrySet like so:

public static void printMap(Map mp) {
    Iterator it = mp.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        System.out.println(pair.getKey() + " = " + pair.getValue());
        it.remove(); // avoids a ConcurrentModificationException
    }
}

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()) {
    // ...
}

Don't want to miss updates? Please click the below button!

Follow MindStick