Today, a friend asked me about the traversal of the MAP collection. It was really stunned at the time.
Public Static Void Main (String [] ARGS) {Map <string, String> Map = New HashMap <string, String> (); Map.put ("1", "Zhang San"); Map.put ("2" , "Li Si"); Map.put ("3", "Wang Wu");}
The first method: traversed through the Map.keySet through key and value
For (string key: map.keyset ()) {system.out.print ("key ="+key); system.out.println ("value ="+map.get (key));}
The second method: traversing Map through map.entrySet and iterators
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 ());}
The third method: map.entryset () plus for in loop (recommendation):
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.entry is an interface that indicates a key value (mapping item), and set <Map <k, v >> means indicating SET of the mapping item.
The fourth method: via map.values ():
for (string value: map.values ()) {system.out.println ("value ="+v);}
The above four methods introduced the traversal code of the MAP collection, hoping to help everyone.