Summary of the traversal of the Map set and the summary of the map set
The traversal of a Map set is often encountered. Today we will summarize several methods of traversing a Map set:
1 public static void main (String [] args) {2 Map <String, String> map = new HashMap <String, String> (); 3 map. put ("1", "Zhang San"); 4 map. put ("2", "Li Si"); 5 map. put ("3", "Wang Wu"); 6 7}
1 for (String key: map. keySet () {2 System. out. print ("key =" + key); 3 System. out. println ("value =" + map. get (key); 4 5}View Code
2. Traverse Map through Map. entrySet and iterator
Iterator<Map.Entry<String,String>> car =map.entrySet().interator(); while(car.hasNext()){ Map.Entry<String,String> entry=car.next(); System.out.println("key="+entry.getKey()+"and value="+entry.getValue()); }
3. Map. entrySet () plus for in loop (recommended ):
for(Map.Entry<String,String> entry:map.entrySet()){ System.out.println("key="+entry.getKey()+"and value="+entry.getValue());}
Note: Map. entrySet () returns a Set <Map <k, v>, Map. an Entry is an interface that represents a key-Value Pair (ing item), and Set <Map <k, v> indicates the Set of the ing item.
4. Map. values ():
for(String val:map.Values()){ System.out.println("value="+v);}