Sorted out four ways to traverse a map in Java:
Import Java.util.hashmap;import java.util.iterator;import Java.util.map;import Java.util.map.entry;import Java.util.set;publicclassmaptest{privatemap<string,string> Map;publicmaptest () {
Map =newhashmap<string,string> ();
Map.put ("1", "first number");
Map.put ("2", "second number");
map.put ("3", "third Number");} The first method (traditional method) Publicvoid Mapone () {set<string> Set = Map.keyset ();iterator<string> it = Set.iterator (); while (It.hasnext ()) {string key = (String) it.next (); String value = (string) map.get (key); SYSTEM.OUT.PRINTLN (key + "=" + value);} The second method (traditional method) Publicvoid Maptwo () {Set set = Map.entryset (); Iterator it = Set.iterator (); while (It.hasnext ()) {Entry Entry = (Entry) it.next (); String key = (string) entry.getkey (); String value = (string) entry.getvalue (); SYSTEM.OUT.PRINTLN (key + "=" + value);} The third method (enhanced for-loop method) Publicvoid Mapthree () {for (Object Obj:map.keySet ()) {String key = (string) obj; String value = (string) map.get (key); SYSTEM.OUT.PRINTLN (key + "=" + value);} The fourth method (enhanced for-loop method) Publicvoid Mapfour () {for (Object Obj:map.entrySet ()) {Entry Entry = (Entry) obj; String key = (string) entry.getkey (); String value = (string) entry.getvalue (); SYSTEM.OUT.PRINTLN (key + "=" + value);} Publicstaticvoid Main (string[] args) {maptest maptest =newmaptest (); System.out.println ("=====first===== ");
Maptest.mapone (); System.out.println ("=====second=====");
Maptest.maptwo (); System.out.println ("=====three=====");
Maptest.mapthree (); System.out.println ("=====four=====");
Maptest.mapfour ();} Output results:
=====first=====3= Third Number 2 = second Number 1 = first number =====second=====3= Third number 2 = second Number 1 = first number =====three=====3= Third number 2 = second Number 1 = first number =====four= ====3= Third Number 2 = second Number 1 = first number