Based on the map structure, there are three traversal methods:
1. traverse through keys;
2. traverse through key + value;
3. traverse through value.
Different traversal methods are used according to specific requirements. The second method is commonly used. However, when the data volume is small and the key value is a relatively simple numeric string, the first method is faster than the second method, the first method can be considered.
According to Java syntax, there can be two statements:
1. Use the for loop;
2. Use iterator for iteration;
The efficiency of the two methods is similar; the use of the For Loop is slightly better;
The specific traversal code is as follows:
Package COM. my. project; import Java. util. hashmap; import Java. util. iterator; import Java. util. map; // map traversal methods: public class travelmap {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 "); /* =, traverse through key =================================================== ==== * // For Loop syntax for (string key: map. keyset () {system. out. println ("Key =" + key); system. out. println ("value =" + map. get (key);} // iterative Writing Method iterator <string> ite = map. keyset (). iterator (); While (ITE. hasnext () {string key = ite. next (); string value = map. get (key) ;}/ * =========================second, through iterative traversal =================================================== ==== * // For Loop statement, use for (map. entry <string, string> entry: map. entryset () {string key = entry. getkey (); string value = entry. getvalue (); system. out. println ("Key =" + key); system. out. println ("value =" + value);} // iterative Writing Method iterator <map. entry <string, string> it = map. entryset (). iterator (); While (it. hasnext () {map. entry <string, string> entry = it. next (); string key = entry. getkey (); string value = entry. getvalue (); system. out. println ("Key =" + key); system. out. println ("value =" + value );} /* =, traverse through value =================================================== ==== */For (string value: map. values () {system. out. println (value );}}}