在Java项目中,常常会涉及到Map的遍历。然而,不同的方式遍历Map时,效率是不一样的。我总结了一下,可能会有的4种方式来实现Map的遍历。
1. 使用enrtySet()for each遍历
for (Map.Entry<String,Integer> entry : testMap.entrySet()) { //entry.getKey(); //entry.getValue(); }2. 使用 keySet() for each 遍历
for (String key : testMap.keySet()) { //testMap.get(key); }3. 使用 enrtySet() 迭代遍历
Iterator<Map.Entry<String,Integer>> itr1 = testMap.entrySet().iterator(); while(itr1.hasNext()){ Map.Entry<String,Integer> entry = itr1.next(); //entry.getKey(); //entry.getValue(); }4. 使用 keySet()迭代遍历
Iterator itr2 = testMap.keySet().iterator(); while(itr2.hasNext()) { String key = itr2.next(); testMap.get(key); }
public class ComparingMapLoop { private static int MAP_SIZE = 1000000; private static Map<String, Integer> testMap = new HashMap<String, Integer>(MAP_SIZE); static { for (int i = 0; i < MAP_SIZE; i++) { testMap.put("key_" + i, i); } } public void testMapLoop() { long startTime = Calendar.getInstance().getTimeInMillis(); //First way using entrySet in for-each loop for (Map.Entry<String, Integer> entry : testMap.entrySet()) { entry.getKey(); entry.getValue(); } System.out.println("Using entrySet() in for-each loop : " + (Calendar.getInstance().getTimeInMillis() - startTime)); startTime = Calendar.getInstance().getTimeInMillis(); //Second way using keySet() in for-each loop for (String key : testMap.keySet()) { testMap.get(key); } System.out.println("Using keySet() in for-each loop : " + (Calendar.getInstance().getTimeInMillis() - startTime)); startTime = Calendar.getInstance().getTimeInMillis(); //Third way using Iterator on entrySet() in while loop Iterator<Map.Entry<String, Integer>> itr1 = testMap.entrySet().iterator(); while (itr1.hasNext()) { Map.Entry<String, Integer> entry = itr1.next(); entry.getKey(); entry.getValue(); } System.out.println("Using entrySet() and iterator : " + (Calendar.getInstance().getTimeInMillis() - startTime)); startTime = Calendar.getInstance().getTimeInMillis(); //Third way using Iterator on keySet() in while loop Iterator<String> itr2 = testMap.keySet().iterator(); while (itr2.hasNext()) { String key = itr2.next(); testMap.get(key); } System.out.println("Using keySet() and iterator : " + (Calendar.getInstance().getTimeInMillis() - startTime)); } public static void main(String[] args) { new ComparingMapLoop().testMapLoop(); } }
Using entrySet() in for-each loop : 62
Using keySet() in for-each loop : 89
Using entrySet() and iterator : 58
Using keySet() and iterator : 81
你可以立马就可以下一个结论,使用entry set 产生的性能相对于key set 迭代来说更强大。当然,其根本原因是使用迭代的方式不同, key set 会两次去执行Map检索查找对已的key-value键值对。