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"); First: Universally used, two times value System.out.println ("Traverse key and value by Map.keyset"); For (String Key:map.keySet ()) {System.out.println ("key=" + key + "and value=" + map.get (key)); }//second type of SYSTEM.OUT.PRINTLN ("Traverse key and value by Map.entryset using iterator"); 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 ()); }//Third type: recommended, especially when the capacity is large System.out.println ("Traverse key and value through Map.entryset"); for (Map.entry<String, String>Entry:map.entrySet ()) {System.out.println ("key=" + entry.getkey () + "and value=" + entry.getvalue ()); }//Fourth type SYSTEM.OUT.PRINTLN ("Traverse all the value through Map.values (), but cannot traverse key"); For (String v:map.values ()) {System.out.println ("value=" + V); } }
Four ways to traverse a map