Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


How to iterate through a HashMap in Java

Damian99Damian99 USAMember Posts: 116

What is the best way to iterate through a HashMap in Java?



  • DavidMDavidM USAMember Posts: 342
    edited January 2014
    public static void printMyMap(Map map) {
        Iterator itr = map.entrySet().iterator();
        while (itr.hasNext()) {
            Map.Entry pairs = (Map.Entry);
            System.out.println(pairs.getKey() + " = " + pairs.getValue());
            itr.remove(); // avoids  ConcurrentModificationException
  • GouthamKumarGouthamKumar NelloreMember Posts: 17

    Iterating over any of the Map implementation(Hashmap, TreeMap etc) is not very straight forward compared to other collections There are different ways you can iterate over Map, to iterate using advanced for loop and using the Iterator object. We will use following three different ways to traverse.
    Using entrySet() and for loop
    Using keyset() and for loop
    Using Iterator interface
    For clear understanding and for examle programs please follow the link

Sign In or Register to comment.