Packagegather;ImportJava.util.HashMap;ImportJava.util.Iterator;ImportJava.util.Map; Public classEchoMap { Public Static voidMain (string[] args) {Map<String,String> map =NewHashmap<string,string>(); Map.put ("1", "value1"); Map.put ("2", "value2"); Map.put ("3", "Value3"); Map.put ("4", "Value4"); //The first way: universal use, two times valueSystem.out.println ("Using Iterator to traverse key and value through Map.entryset"); for(String key:map.keySet ()) {System.out.println ("Key=" +key+ "and value=" +Map.get (key)); } //The second way:System.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 Way: Recommended use: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 WaySystem.out.println ("Traverse all value through Map.values (), but cannot traverse key"); for(String value:map.values ()) {System.out.println ("Value:" +value); } } }
Java Map Interface 4 in the traversal mode