Iterator returned by entrySet() and keySet() methods can be used to iterate a HashMap in Java
Let us look at the code for the iterator using both entrySet() and keySet() methods:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class Tech4Humans {
public static void main(String[] args)
{
HashMap<Integer,String> map2 = new HashMap<Integer,String>();
map2.put(10, "This");
map2.put(20, "Bye");
map2.put(30, "Say");
map2.put(40, "Great");
System.out.println("HashMap iterating using entrySet() iterator:");
//iterating HashMap using entrySet() iterator
Iterator iter1 = map2.entrySet().iterator();
while(iter1.hasNext())
{
Map.Entry<Integer, String> mapBucket = (Map.Entry) iter1.next();
System.out.println("Key = "+mapBucket.getKey()+", Value = "+mapBucket.getValue());
}
System.out.println("\nHashMap iterating using keySet() iterator:");
//iterating HashMap using keySet() iterator
Iterator iter2 = map2.keySet().iterator();
while(iter2.hasNext())
{
Integer mapKey = (Integer) iter2.next();
System.out.println("Key = "+mapKey+", Value = "+map2.get(mapKey));
}
}
}
Output
HashMap iterating using entrySet() iterator:
Key = 20, Value = Bye
Key = 40, Value = Great
Key = 10, Value = This
Key = 30, Value = Say
HashMap iterating using keySet() iterator:
Key = 20, Value = Bye
Key = 40, Value = Great
Key = 10, Value = This
Key = 30, Value = Say