Saturday, 16 August 2014

Multiple way to Iterate HashMap


Map is a collection of key and value pair. There are multiple way to iterate a map. In this code snippet, four ways to iterate a map are displayed.


package coreCollection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class IterateMap {

/**
* @param args
*/
public static void main(String[] args) {

Map<Integer, String> map=new HashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
map.put(5, "five");


//first way.
Set<Integer> keySet=map.keySet();
Iterator<Integer> itr=keySet.iterator();
while(itr.hasNext()){
Integer key=(Integer)itr.next();
System.out.println("value : "+map.get(key));
}
System.out.println("\n");


//second way.
Collection<String> col=map.values();
Iterator ir=col.iterator();
while(ir.hasNext()){
 System.out.println("value : "+ir.next());
}
System.out.println("\n");


//third way.
Set kySet=map.entrySet();
Iterator itrr=kySet.iterator();
while(itrr.hasNext()){
Map.Entry<Integer, String> entry=(Entry<Integer, String>) itrr.next();
System.out.println("Value : "+entry.getValue());
}
System.out.println("\n");


//Fourth way.
Set s=map.keySet();
List ll=new ArrayList(s);
for(int i=0;i<ll.size(); i++){
System.out.println("value : "+map.get(ll.get(i)));
}
System.out.println("\n");
}
}

Output:



No comments:

Post a Comment