Traversing Map interface is bit differ
from traversing the collection interface because we have key, Value pair is
stored in map and we have to traverse them as a set. We use some properties of
Map interface to do the work like Map.Entry, Map.entryset(), which are used to
tackle key, value pair as set. We can get the value of key and value with
getKey() and getValue() methods from object of Map.Entry type. Please see the
program below to understand it more clearly.
In below examples, we traversed both
HashMap and Hashtable. There is no difference between traversing of them, the
only difference is the output of both program.
The HashMap produce a sorted output but Hashtable produce a unsorted output (As per their
properties).
1 - Traverse
HashMap with Iterator Example:
import java.util.*;
public class
demoTraverseHashMap
{
public static void main(String s[])
{
Map mp = new HashMap();
mp.put(1,"First");
mp.put(2,"Second");
mp.put(3,"Third");
mp.put(4,"Fourth");
System.out.println("Print MAP
contents without traversing");
System.out.println(mp);
System.out.println("Print MAP
contents with Iterator traversing");
Iterator it = mp.entrySet().iterator();
while(it.hasNext())
{
Map.Entry pairs = (Map.Entry) it.next();
System.out.println("Key :
"+pairs.getKey()+",
Value : "+pairs.getValue());
}
}
}
OutPut:
Print MAP contents without
traversing
{1=First, 2=Second, 3=Third,
4=Fourth}
Print MAP contents with
Iterator traversing
Key : 1, Value : First
Key : 2, Value : Second
Key : 3, Value : Third
Key : 4, Value : Fourth
2 - Traverse
HashTable with Iterator Example:
import java.util.*;
public class demoTraverseHashMap
{
public static void main(String s[])
{
Map mp = new Hashtable();
mp.put(1,"First");
mp.put(2,"Second");
mp.put(3,"Third");
mp.put(4,"Fourth");
System.out.println("Print MAP
contents without traversing");
System.out.println(mp);
System.out.println("Print MAP
contents with Iterator traversing");
Iterator it = mp.entrySet().iterator();
while(it.hasNext())
{
Map.Entry pairs = (Map.Entry) it.next();
System.out.println("Key :
"+pairs.getKey()+",
Value : "+pairs.getValue());
}
}
}
OutPut:
Print MAP contents without
traversing
{4=Fourth, 3=Third, 2=Second,
1=First}
Print MAP contents with
Iterator traversing
Key : 4, Value : Fourth
Key : 3, Value : Third
Key : 2, Value : Second
Key : 1, Value : First