Public static void main (string [] ARGs) {Map <string, string> map = new hashmap <string, string> (); map. put ("1", "value1"); map. put ("2", "value2"); map. put ("3", "value3"); // the first type is commonly used. The second value is system. out. println ("through map. keyset traversal key and value: "); For (string key: map. keyset () {system. out. println ("Key =" + key + "and value =" + map. get (key);} // second system. out. println ("through map. entryset uses iterator to Traverse Key and value: "); 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 ();} // The third type is recommended, especially when the capacity is large. out. println ("through map. entryset traverses key and value "); For (map. entry <string, string> entry: map. entryset () {system. out. println ("Key =" + entry. getkey () + "and value =" + entry. getvalue ();} // The fourth system. out. println ("through map. values () traverses all values, but cannot Traverse Key "); For (string V: map. values () {system. out. println ("value =" + V );}}
Four Methods for Traversing Map