Wednesday, January 31, 2007

Iterating through a Hash Map

Lets say you have a hash map

Map currencyMap=new HashMap();

currencyMap=someMapYouGot();

//YOu can iterate thru this map using either the entry set or key set

//here is how

Iterator iterator=currencyMap.keySet().Iterator;

while(iterator.hasNext()){
Object key=iterator.next();

System.out.printn("Key is :"+key.toString());

Object value=currencyMap.get(key);


System.out.println("Value is :"+value.toString());

}

//Other way of doing is:

Iterator iterator=currencyMap.entrySet().iterator;

while(iterator.hasNext()){

Map.Entry entry=(Entry)iterator.next();

Object key=entry.getKey();

Object value=entry.getValue();


}
}


//Yet another way of doing is create a collection of values from the map and iterate thru the list:)

//Here is how

List list=new ArrayList();

Collection coll=currencyMap.values();

list.addAll(coll);


--Happy Coding





}

No comments: