Four ways to traverse a map
Public classMaptest { Public Static voidMain (string[] args) {Map<string, string> maps =NewHashmap<string, string>(); Maps.put ("K1", "value1"); Maps.put ("K2", "value2"); Maps.put ("K3", "Value3"); Test1 (maps);//test2 (maps);//test3 (maps);//test4 (maps); } //The first type: Universal use, two-time value Public Static voidTest1 (map<string, string>maps) {System.err.println ("Traversing key and value through Map.keyset"); for(String key:maps.keySet ()) {System.out.println ("Key:" +key+ "--->value:" +Maps.get (key)); } } //The second type: Use iterator to traverse key and value via Map.entryset Public Static voidTest2 (map<string, string>maps) {System.err.println ("Using iterator to traverse key and value through Map.entryset:"); Iterator<map.entry<string, string>> it =Maps.entryset (). iterator (); while(It.hasnext ()) {Map.entry<string, string> entry =It.next (); System.out.println ("Key:" +entry.getkey () + "--->value:" +Entry.getvalue ()); } } //the third type: recommended, especially when the capacity is large Public Static voidTest3 (map<string, string>maps) {System.err.println ("Traversing key and value through Map.entryset"); for(Map.entry<string, string>Entry:maps.entrySet ()) {System.out.println ("Key:" +entry.getkey () + "--->value:" +Entry.getvalue ()); } } //Fourth Type Public Static voidTest4 (map<string, string>maps) {System.out.println ("Traverse all value through Map.values (), but cannot traverse key"); for(String str:maps.values ()) {System.out.println ("Value:" +str); } }}
Four ways to traverse a map