ImportJava.util.HashMap;ImportJava.util.Iterator;ImportJava.util.Map; Public classTestMap { Public Static voidMain (string[] args) {Map<integer, string> map =NewHashmap<integer, string>(); Map.put (1, "a"); Map.put (2, "B"); Map.put (3, "AB"); Map.put (4, "AB"); Map.put (4, "AB");//same as above, will filter by itselfSystem.out.println (Map.size ()); //The first type: /** set<integer> set = Map.keyset ();//Get a collection of all keys * * for (Integer in:set) {String St R = Map.get (in); * SYSTEM.OUT.PRINTLN (In + "" + str);}*/System.out.println ("First: Traverse key and value through Map.keyset:"); for(Integer in:map.keySet ()) {//Map.keyset () returns the value of all keysString str = Map.get (in);//get the value of multiple pairs with value for each keySystem.out.println (In + "" +str); } //The second type:System.out.println ("Second type: Using iterator to traverse key and value through Map.entryset":); Iterator<map.entry<integer, string>> it =Map.entryset (). iterator (); while(It.hasnext ()) {Map.entry<integer, 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 ("Third: traversal of key and value through Map.entryset"); for(Map.entry<integer, string>Entry:map.entrySet ()) { //There are several ways to map.entry<integer,string> mapping entries (key-value pairs): Use the name above entry//Entry.getkey (); Entry.getvalue (); Entry.setvalue (); //Map.entryset () returns the set view of the mapping relationships contained in this map. System.out.println ("key=" + entry.getkey () + "and value=" +Entry.getvalue ()); } //The fourth type:System.out.println ("Fourth: Traverse all the value through Map.values (), but cannot traverse key"); for(String v:map.values ()) {System.out.println ("Value=" +v); } }}
Iteration of the map collection in Java