Advertise with us

What is the best way to iterate on hashmap in java

What's the best way to iterate over the items in a HashMap?
Last updated:7/27/2015 8:36:16 AM

1 Answers

Mayank Tripathi
Mayank Tripathi

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
    }
}

Last updated:7/27/2015 8:36:16 AM

Answer