Map traversal and Map Traversal
Public class Mapper {
Public static void main (String [] args ){
Map <String, String> map = new HashMap <String, String> ();
Map. put ("1", "v1 ");
Map. put ("2", "v2 ");
Map. put ("3", "v3 ");
// Type 1: traverse the key and obtain the corresponding value through the key.
System. out. println ("Traverse key and value through Map. keySet :");
For (String key: map. keySet ()){
System. out. println ("key =" + key + "and value =" + map. get (key ));
}
// Method 2: Use an Entry, especially when the capacity is large.
System. out. println ("traversing key and value through Map. entrySet ");
For (Map. Entry <String, String> entry: map. entrySet ()){
System. out. println ("key =" + entry. getKey () + "and value =" + entry. getValue ());
}
// Type 3: iterator
System. out. println ("Traverse key and value through Map. entrySet using iterator :");
Iterator <Map. Entry <String, String> it = map. entrySet (). iterator ();
While (it. hasNext ()){
Map. Entry <String, String> entry = it. next ();
System. out. println ("key =" + entry. getKey () + "and value =" + entry. getValue ());
}
// Type 4: traverse value only
System. out. println ("traverse all values through Map. values (), but not key ");
For (String v: map. values ()){
System. out. println ("value =" + v );
}
}
}