今天来搞一次HashMap 遍历的操作方式:
经过测试,方式一的效率要远高于方式二.,1000000条测试数据,第一种大概耗时20多秒,第二种耗时大概40多秒.所以,建议以后使用第一种方式.
直接上代码:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class testHashMap {
static Map<Object, Object> map;
static long begin;
static long end;
public static void main(String[] args) {
map = new HashMap<Object, Object>();
for (int i = 0; i < 1000000; i++) {
map.put("map" + i, i);
}
// 第一种:
Iterator<Entry<Object, Object>> iter = map.entrySet().iterator();
begin = System.currentTimeMillis();
while (iter.hasNext()) {
Entry<Object, Object> entry = iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
// System.out.println("["+key+","+val+"]");
}
end = System.currentTimeMillis();
System.out.println("第一种,耗时" + (end - begin));
// 第二种:
Iterator<Object> iter1 = map.keySet().iterator();
begin = System.currentTimeMillis();
while (iter1.hasNext()) {
Object key = iter1.next();
Object val = map.get(key);
// System.out.println("["+key+","+val+"]");
}
end = System.currentTimeMillis();
System.out.println("第二种,耗时" + (end - begin));
}
}