Tutorials

Java Collection Programs


HashMap traversal


In this chapter, our task is:

  • We will create a HashMap
  • We will add elements to HashMap
  • We will traverse the map
  • We will print the elements

Example: Traverse the map using iterator in java

 


package HashMap;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HashMapTraversal {

      public static void main(String a[]){
     
           //create hashmap
            Map m = new HashMap();
           
           //add (key, value) pair to hashmap
            m.put("a", 1);
            m.put("b", 2);
            m.put("c", 3);
            m.put("d", 4);
            m.put("e", 55);
          
           //create iterator to traverse over map
            Iterator i = m.entrySet().iterator();

            while(i.hasNext()){

                  Map.Entry entry = (Map.Entry) i.next();
                  System.out.println("Key : " + entry.getKey() + " Value :" + entry.getValue());

            }

      }

}

OUTPUT

Key : a Value :1
Key : b Value :2
Key : c Value :3
Key : d Value :4
Key : e Value :55


Please Share this page
Views : 112
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!