Thursday 19 January 2012

Iterate over hashmap


public static void iterateOverHashmapGeneric(){


 HashMap<String, Integer> hm1 = new HashMap<String, Integer>();
 hm1.put("E", 69);
 hm1.put("A", 65);
 hm1.put("G", 71);
 hm1.put("C", 67);

 Set<String> mySet = hm1.keySet();
 System.out.print("foreach printing: ");
 for(String str : mySet)
 {
  System.out.print(str + ":" + hm1.get(str) + ", ");
 }

 HashMap<String, Integer> hm2 = new HashMap<String, Integer>();
 hm2.putAll(hm1);
 if(hm1.equals(hm2))
 {
  System.out.println("\n\nhm1 and hm2 contain the same elements");
 }

 HashMap<String, Integer> hm3 = (HashMap) hm1.clone();
 System.out.println("\nElements of hm3: " + hm3);   

}



A generics HashMap object hm1 is created that stores keys as strings and values as integers. With put() method elements are added.
Set<String> mySet = hm1.keySet();
     for(String str : mySet)
     {
       System.out.print(str + ":" + hm1.get(str) + ", ");
     }
With HashMap, Iterator cannot be used as Iterator stores elements of single entities but HashMap stores pairs. The new JDK 1.5 enhanced for loop (foreach) cannot be used straight away for the same reason. It is used indirectly. The keySet() returns all the keys of HashMap hm1. As keys are single entities, to iterate them, foreach loop is used. The str refers a key and using the key str, the value associated is retrieved with get() method.
HashMap<String, Integer> hm2 = new HashMap<String, Integer>();
     hm2.putAll(hm1);
     if(hm1.equals(hm2))
     {
       System.out.println("\n\nhm1 and hm2 contain the same elements");
     }
Another generics object hm2 is created and all the elements of hm1 are added at a time with putAll() method. equals() method is used to check both hm1 and hm2 contains the same elements are not. As they have same, the method returns true.
HashMap<String, Integer> hm3 = (HashMap) hm1.clone();
     System.out.println("\nElements of hm3: " + hm3);
Any Collection object including HashMap can be cloned. As the cloned object, hm3 and the hm1 occupy different locations and have their own set of values, they maintain perfect encapsulation.

No comments:

Post a Comment