向map中添加數據 150萬
Map<String,String> m = new HashMap<>(); for (int i = 0; i < 1500000; i++) { m.put("a" + i,"1"); } long start2 = System.currentTimeMillis(); Set<Map.Entry<String, String>> entries1 = m.entrySet(); Iterator<Map.Entry<String, String>> iterator = entries1.iterator(); while (iterator.hasNext()){ Map.Entry<String, String> next = iterator.next(); System.out.println(next.getKey() + next.getValue()); } long iteratorTime = System.currentTimeMillis() - start2; long start = System.currentTimeMillis();for (Map.Entry<String, String> entry : m.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } long entrySetTime = System.currentTimeMillis() - start; long start1 = System.currentTimeMillis(); for (String s : m.keySet()) { System.out.println(s + " " + m.get(s)); } long keySetTime = System.currentTimeMillis() - start1; System.out.println("iteratorTime" + iteratorTime); System.out.println("entrySetTime" + entrySetTime); System.out.println("keySetTime" + keySetTime);
第一次運行的結果:
iteratorTime5556
entrySetTime5620
keySetTime5779spa
第二次運行結果code
iteratorTime5194
entrySetTime5267
keySetTime5296blog
再運行幾回 get
iteratorTime5465
entrySetTime5594
keySetTime5703it
map數據是10萬左右的時候運行屢次,結果就不同了,三個都有最快的時候,不知道爲何,可是從數據最多的狀況來分析,仍是iterator方式遍歷的速度是最快的。class
因此,咱們使用中爲了速度,咱們使用iterator遍歷
寫代碼簡單map
keySet和entrySet 省事兒