1. Iterate by constructing HashMap's EntrySet
Public classTestunit { Public Static voidMain (string[] args) {HashMap HashMap=NewHashmap<integer,string>(); Hashmap.put (1, "AAA"); Hashmap.put (2, "BBB"); Hashmap.put (3, "CCC"); Iterator ITER=Hashmap.entryset (). iterator (); while(Iter.hasnext ()) {Map.entry Mapentry=(Map.entry) iter.next (); Object Key=Mapentry.getkey (); Object value=Mapentry.getvalue (); System.out.println ("Key=" +key+ ", value=" +value); } }}
2. Obtain the HashMap keyset first, and then use Get (key) to access
if (hashmap!=null | |! Hashmap.isempty ()) { Set Set=hashmap.keyset (); Iterator iter=set.iterator (); while (Iter.hasnext ()) { Object key=iter.next (); Object value=hashmap.get (key); System.out.println ("key=" +key+ ", value=" +value); } }
Test
It is said to use EntrySet a bit faster, write a piece of code test, it is true.
Public classTestunit { Public Static voidMain (string[] args) {HashMap<integer, string> HashMap =NewHashMap (); for(inti = 0; i < 1000; i++) {hashmap.put (I,"Hello world!"); } keysettest (HASHMAP); Entrysettest (HASHMAP); } Static voidkeysettest (map map) {LongStartTime =calendar.getinstance (). Gettimeinmillis (); Iterator ITER=Map.keyset (). iterator (); while(Iter.hasnext ()) {System.out.print (Map.get (Iter.next ())); } LongEndTime =calendar.getinstance (). Gettimeinmillis (); System.out.println ("\nkeysettest:" + (Endtime-starttime));//Ms } Static voidentrysettest (map map) {LongStartTime =calendar.getinstance (). Gettimeinmillis (); Iterator ITER=Map.entryset (). iterator (); Map.entry Mapentry; while(Iter.hasnext ()) {Mapentry=(Map.entry) iter.next (); System.out.print (Mapentry.getvalue ()); } LongEndTime =calendar.getinstance (). Gettimeinmillis (); System.out.println ("\nentrysettest:" + (Endtime-starttime));//Ms }}View Code
Cause Analysis:
- When accessed using the Keyset method, the built set consists only of key, and the hash value is recalculated when each value is accessed and then the value is found in the map based on the hash values;
- When accessed using the EntrySet method, the built set is composed directly of <key,value>, which accesses each value directly, without calculating the hash value.
Java-hashmap Iteration