1.java遍历map对象的5种方法效率比较
Map map = new HashMap();
for (int i = 0; i < 10000; i++) {
map.put("book" + i, 9.9D);
map.put("ipad" + i, 1300D);
map.put("pen" + i, 8D);
}
//方法1 (java8)
long start1 = System.currentTimeMillis();
map.forEach((key, value) -> System.out.println(key + " ==> " + value));
long end1 = System.currentTimeMillis();
//方法2
long start2 = System.currentTimeMillis();
for (Map.Entry entry: map.entrySet()){
System.out.println(entry.getKey() + " ==> " + entry.getValue());
}
long end2 = System.currentTimeMillis();
//方法3
long start3 = System.currentTimeMillis();
Iterator> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = iterator.next();
System.out.println(entry.getKey() + " ==> " + entry.getValue());
}
long end3 = System.currentTimeMillis();
//方法4
long start4 = System.currentTimeMillis();
for (Object key : map.keySet()) {
System.out.println(key + " ==> " + map.get(key));
}
long end4 = System.currentTimeMillis();
//方法5
long start5 = System.currentTimeMillis();
//遍历map中的键
for (String key : map.keySet()) {
System.out.println("Key = " + key);
}
//遍历map中的值
for (Double value : map.values()) {
System.out.println("Value = " + value);
}
long end5 = System.currentTimeMillis();
System.out.println("time1 foreach " + (end1 - start1));
System.out.println("time2 for " + (end2 - start2));
System.out.println("time3 while " + (end3 - start3));
System.out.println("time4 for " + (end4 - start4));
System.out.println("time5 while " + (end5 - start5));
2.分情况讨论效率
a.map的size值在10内
time1 foreach 2
time2 for 1
time3 while 0
time4 for 1
time5 while 1
b.map的size值在100内
time1 foreach 8
time2 for 7
time3 while 3
time4 for 5
time5 while 6
c.map的size值在1000内
time1 foreach 27
time2 for 18
time3 while 17
time4 for 19
time5 while 22
d.map的size值在10000内
time1 foreach 207
time2 for 145
time3 while 121
time4 for 145
time5 while 250
3.结论
由2结果可知,推荐使用方法3,效率最高