Import Java. util. calendar; import Java. util. map; import Java. util. hashmap; import Java. util. iterator; import Java. util. set; public class hashmaptest {<span style = "white-space: pre"> </span> Public static void main (string [] ARGs) {<span style = "white-space: pre"> </span> <span style = "white-space: pre"> </span> Map <integer, string> map = new hashmap <integer, string> (); <span style = "white-space: pre"> </span> for (INT I = 0; I <= 5000000; I ++) {<span style = "white-space: pre"> </span> map. put (I, "a" + I); <span style = "white-space: pre" ></ span >}< span style = "white-space: pre "> </span> // Traversal method 1 <span style =" white-space: pre "> </span> set = map. keyset (); <span style = "white-space: pre"> </span> iterator iterator1 = set. iterator (); <span style = "white-space: pre"> </span> <span style = "white-space: pre "> </span> long starttime1 = calendar. getinstance (). gettimeinmillis (); // start time <span style = "white-space: pre"> </span> <span style = "white-space: pre "> </span> while (iterator1.hasnext () {<span style =" white-space: pre "> </span> Object key = iterator1.next (); <span style = "white-space: pre"> </span> object value = map. get (key); <span style = "white-space: pre"> </SPAN >}< span style = "white-space: pre "> </span> long endtime1 = calendar. getinstance (). gettimeinmillis (); <span style = "white-space: pre"> </span> system. out. println ("costtime1 =" + (endtime1-starttime1); // end time <span style = "white-space: pre "> </span> <span style =" white-space: pre "> </span> // method 2 <span style =" white-space: pre "> </span> iterator iterator2 = map. entryset (). iterator (); <span style = "white-space: pre"> </span> long starttime2 = calendar ar. getinstance (). gettimeinmillis (); // start time <span style = "white-space: pre"> </span> while (iterator2.hasnext () {<span style = "white-space: pre "> </span> map. entry <integer, string> entry = (map. entry <integer, string>) iterator2.next (); <span style = "white-space: pre"> </span> Object key = entry. getkey (); <span style = "white-space: pre"> </span> Object val = entry. getvalue (); <span style = "white-space: pre"> </SPAN >}< span style = "white-space: pre "> </span> long endtime2 = calendar. getinstance (). gettimeinmillis (); // end time <span style = "white-space: pre"> </span> system. out. println ("costtime2 =" + (endtime2-starttime2); <span style = "white-space: pre" ></ span> }}
Output result:
Costtime1 = 145costtime2 = 78