一、通过keySet进行遍历
- 一般适用于只需要Map中key的时候使用,通过key来get对应的value值效率较低,比较耗时;
public static void showMapWithKeySet(Map<String, Integer> userMap) {
Long start = System.currentTimeMillis();
for (String key : userMap.keySet()) {
System.out.println(key + "---" + userMap.get(key));
}
Long end = System.currentTimeMillis();
System.out.println("iterator time = " + (end - start));
}
二、通过values进行遍历
public static void showMapWithValues(Map<String, Integer> userMap) {
Long start = System.currentTimeMillis();
for (Integer value : userMap.values()) {
System.out.println(value);
}
Long end = System.currentTimeMillis();
System.out.println("iterator time = " + (end - start));
}
三、通过entrySet进行遍历
- 大多数情况下用的最多的也是最常见的,一般在键值对都需要使用,entrySet比keySet遍历的效率高很多;
public static void showMapWithEntrySet(Map<String, Integer> userMap) {
for (Map.Entry<String, Integer> mapEntry : userMap.entrySet()) {
System.out.println(mapEntry.getKey() + "----" + mapEntry.getValue());
}
Long end = System.currentTimeMillis();
System.out.println("iterator time = " + (end - start));
}
四、通过iterator(迭代器)进行遍历
- iterator的遍历方式比for循环遍历效率要高;
public static void showMapWithIterator(Map<String, Integer> userMap) {
Long start = System.currentTimeMillis();
Iterator<Map.Entry<String, Integer>> it = userMap.entrySet().iterator();
while (it.hasNext()) {
it.next();
Map.Entry<String, Integer> entry = it.next();
System.out.println(entry.getKey() + "===" + entry.getValue());
}
Long end = System.currentTimeMillis();
System.out.println("iterator time = " + (end - start));
}
五、性能对比(HashMap)
- 在实验的时候保证每个遍历的方法实验环境相当,我们在每个for循环里面执行一次赋值操作以保证实验环境;
- 在这里我执行五次程序以提高实验的准确性
public static Map inputMap() {
Map<String, Integer> userMap = new HashMap<String, Integer>(500000, 0.75f);
String str[] = new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"};
String key;
Integer value;
for (int i = 0; i <= 10000000; i++) {
int m = (int)(Math.random() * 10);
key = String.valueOf(str[m] + i * 100);
value = i;
userMap.put(key, value);
}
return userMap;
}
public static void main(String[] args) {
Map map1 = inputMap();
showMap1(map1);
showMap2(map1);
showMap3(map1);
showMap4(map1);
}
- 各种遍历方式所花费时间对比表格(使用HashMap时):
遍历Map的次数 | keySet Time(ms) | values time(ms) | entrySet time(ms) | iterator time(m’s) |
---|
第一次 | 686 | 443 | 470 | 413 |
第二次 | 697 | 453 | 461 | 401 |
第三次 | 645 | 415 | 447 | 425 |
第四次 | 664 | 452 | 471 | 400 |
第五次 | 632 | 415 | 455 | 387 |
- 得出结论:结果显而易见,四种遍历方式中,在绝大多数的情况下使用iterator方式效率最高,而使用keySet去遍历效率最低;
- 当然这里iterator方式我们使用entrySet方法并转换为迭代器,使用keySet和values方法可能得到不同给的结果,大家有兴趣可以自己去尝试;
- 但是如果只需要得到key值时,keySet遍历方法也许比entrySet更为合适,因为entrySet将value也给取出来了,浪费了空间;大家可以自己测一下在只需要得到key值时keySet和entrySet方式各自的耗时时长;
- 同理,只需要value值时,values遍历方法是最优选择,entrySet会略好于keySet方法;
- 感兴趣可以测一下values和keySet转换为迭代器遍历各自所耗费的时长;