Source
package com.zhaiky;
java.util.HashMap import;
java.util.Iterator import;
import java.util.Map;
java.util.Set import;
public class MapTest {
public static void main(String[] args) {
Map<String,String> map=new HashMap<String,String>();
for(int i=0;i<50000;i++){
map.put("key"+i, "value"+i);
}
String msg="";
//通过Map.entrySet遍历key和value,最常见,效率最高
long starttime=System.currentTimeMillis();
for (Map.Entry<String,String> entry : map.entrySet()) {
msg="Key = " + entry.getKey() + ", Value = " + entry.getValue();
}
long diffe=System.currentTimeMillis()-starttime;
System.out.println("-----------------------------------耗时:"+diffe+"毫秒");
System.out.println(msg);
System.out.println();
By using an iterator Map.entrySet // iterator traversal key and value
the Iterator <of Map.Entry <String, String >> entries It EnumMap.entrySet = () iterator ();.
The while (entries.hasNext ()) {
of Map.Entry < String, String> = entries.next entry ();
MSG = "Key =" entry.getKey + () + ", the Value =" + entry.getValue ();
}
Diffe = System.currentTimeMillis () - startTime;
the System. out.println ( "----------------------------------- Processed:" + diffe + "ms") ;
System.out.println (MSG);
System.out.println ();
// iterate through all value map.values () but not traverse Key
for (String value: map.values ()) {
MSG = "the value = "+ value;
}
= System.currentTimeMillis Diffe () - startTime;
System.out.println ( "--------------------------------- - Processed: "+ diffe +" msec ");
System.out.println (MSG);
System.out.println ();
// get the value of the first key value is then worth values to key
the Set <String> SET = map.keySet ();
for (String Key: SET) {
MSG = "Key =" + Key + ", the Value =" + as map.get (Key);
}
Diffe = System.currentTimeMillis () - startTime;
the System.out .println ( "----------------------------------- Processed:" + diffe + "msec");
System.out.println (MSG);
System.out.println ();
}
}
Test Results
----------------------------------- time: 31 ms
Key = key44663, Value = value44663
----------------------------------- time: 53 ms
Key = key44663, Value = value44663
----------------------------------- time: 68 ms
Value = value44663
----------------------------------- time: 93 ms
Key = key44663, Value = value44663