Public Static voidMain (string[] args) {Map<string, string> map =NewHashmap<string, string>(); Map.put ("1", "value1"); Map.put ("2", "value2"); Map.put ("3", "Value3"); //The first type: Universal use, two-time valueSystem.out.println ("Traverse key and value through Map.keyset:"); for(String key:map.keySet ()) {System.out.println ("key=" + key + "and value=" +Map.get (key)); } //The second KindSystem.out.println ("Using Iterator to traverse key and value through Map.entryset":); 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 ()); } //the third type: recommended, especially when the capacity is largeSystem.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 TypeSystem.out.println ("Traverse all value through Map.values (), but cannot traverse key"); for(String v:map.values ()) {System.out.println ("Value=" +v); } }
Four ways to traverse a map