Ad

Friday 21 August 2009

How to iterate the HashMap?

Map has a Keyset method,which return the set of Keys in the Map.Then by iterating this Set,we can iterate the hashMap values as shown below

Map strMap= new HashMap();
strMap.put("1","one");
strMap.put("2","two");
strMap.put("3","three"); //Construct a HahMap
for(String key:strMap.keySet()) //keySet will give the set of keys                                                               
{
System.out.println("Key - "+key+" Value - "+strMap.get(key));
}

Output will be:
Key - 3 Value - three
Key - 2 Value - two
Key - 1 Value - one

we can iterate the hash map values alone by the Map "values()" method as shown below.
Map "Values()" method will return the collection view of the values present in the hashmap.

for(String value:strMap.values())
{
System.out.println(" Value - "+value);                                                                                                        
}

Output will be
Value - three
Value - two
Value - one

No comments:

Post a Comment