1. Map的四种遍历方式
下面只是简单介绍各种遍历示例(以HashMap为例),各自优劣会在本文后面进行分析给出结论。

(1) for each map.entrySet()

 

Java

 
1
2
3
4
5
Map<String, String> map = new HashMap<String, String>();
for (Entry<String, String> entry : map.entrySet()) {
entry.getKey();
entry.getValue();
}

(2) 显示调用map.entrySet()的集合迭代器

 

Java

 
1
2
3
4
5
6
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
entry.getKey();
entry.getValue();
}

(3) for each map.keySet(),再调用get获取

 

Java

 
1
2
3
4
Map<String, String> map = new HashMap<String, String>();
for (String key : map.keySet()) {
map.get(key);
}

(4) for each map.entrySet(),用临时变量保存map.entrySet()

 

Java

 
1
2
3
4
5
Set<Entry<String, String>> entrySet = map.entrySet();
for (Entry<String, String> entry : entrySet) {
entry.getKey();
entry.getValue();
}

在测试前大家可以根据对HashMap的了解,想想上面四种遍历方式哪个性能更优。

2、HashMap四种遍历方式的性能测试及对比
以下是性能测试代码,会输出不同数量级大小的HashMap各种遍历方式所花费的时间。

HashMap循环遍历方式性能对比测试代码

 

PS:如果运行报异常in thread “main” java.lang.OutOfMemoryError: Java heap space,请将main函数里面map size的大小减小。

其中getHashMaps函数会返回不同size的HashMap。
loopMapCompare函数会分别用上面的遍历方式1-4去遍历每一个map数组(包含不同大小HashMap)中的HashMap。
print开头函数为输出辅助函数,可忽略。

 

测试环境为Windows7 32位系统 3.2G双核CPU 4G内存,Java 7,Eclipse -Xms512m -Xmx512m
最终测试结果如下:

 

Java

 
1
2
3
4
5
6
7
8
9
10
11
12
compare loop performance of HashMap
-----------------------------------------------------------------------
map size               | 10,000    | 100,000   | 1,000,000 | 2,000,000
-----------------------------------------------------------------------
for each entrySet      | 2 ms      | 6 ms      | 36 ms     | 91 ms    
-----------------------------------------------------------------------
for iterator entrySet  | 0 ms      | 4 ms      | 35 ms     | 89 ms    
-----------------------------------------------------------------------
for each keySet        | 1 ms      | 6 ms      | 48 ms     | 126 ms    
-----------------------------------------------------------------------
for entrySet=entrySet()| 1 ms      | 4 ms      | 35 ms     | 92 ms    
-----------------------------------------------------------------------

表横向为同一遍历方式不同大小HashMap遍历的时间消耗,纵向为同一HashMap不同遍历方式遍历的时间消耗。
PS:由于首次遍历HashMap会稍微多耗时一点,for each的结果稍微有点偏差,将测试代码中的几个Type顺序调换会发现,for each entrySet耗时和for iterator entrySet接近。

3、遍历方式性能测试结果分析
(1) foreach介绍
见:ArrayList和LinkedList的几种循环遍历方式及性能对比分析中介绍。

(2) HashMap遍历方式结果分析
从上面知道for each与显示调用Iterator等价,上表的结果中可以看出除了第三种方式(for each map.keySet()),再调用get获取方式外,其他三种方式性能相当。本例还是hash值散列较好的情况,若散列算法较差,第三种方式会更加耗时。
我们看看HashMap entrySet和keySet的源码

 

Java

 
1
2
3
4
5
6
7
8
9
10
11
private final class KeyIterator extends HashIterator<K> {
public K next() {
return nextEntry().getKey();
}
}
 
private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
public Map.Entry<K,V> next() {
return nextEntry();
}
}

分别是keySet()和entrySet()返回的set的迭代器,从中我们可以看到只是返回值不同而已,父类相同,所以性能相差不多。只是第三种方式多了一步根据key get得到value的操作而已。get的时间复杂度根据hash算法而异,源码如下:

 

Java

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public V get(Object key) {
if (key == null)
return getForNullKey();
Entry<K,V> entry = getEntry(key);
 
return null == entry ? null : entry.getValue();
}
 
/**
* Returns the entry associated with the specified key in the
* HashMap.  Returns null if the HashMap contains no mapping
* for the key.
*/
final Entry<K,V> getEntry(Object key) {
int hash = (key == null) ? 0 : hash(key);
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}

get的时间复杂度取决于for循环循环次数,即hash算法。

4、结论总结

从上面的分析来看:
a. HashMap的循环,如果既需要key也需要value,直接用

 

Java

 
1
2
3
4
5
Map<String, String> map = new HashMap<String, String>();
for (Entry<String, String> entry : map.entrySet()) {
entry.getKey();
entry.getValue();
}

即可,foreach简洁易懂。

b. 如果只是遍历key而无需value的话,可以直接用

 

Java

 
1
2
3
4
Map<String, String> map = new HashMap<String, String>();
for (String key : map.keySet()) {
// key process
}

HashMap循环的更多相关文章

  1. HashMap循环遍历方式及其性能对比(zhuan)

    http://www.trinea.cn/android/hashmap-loop-performance/ ********************************************* ...

  2. HashMap循环遍历方式及其性能对比

    主要介绍HashMap的四种循环遍历方式,各种方式的性能测试对比,根据HashMap的源码实现分析性能结果,总结结论.   1. Map的四种遍历方式 下面只是简单介绍各种遍历示例(以HashMap为 ...

  3. hashmap 循环取出所有值 取出特定的值 两种方法

    //第一种 Iterator menus = menu.iterator(); while(menus.hasNext()) { Map userMap = (Map) menus.next(); S ...

  4. hashmap 循环取出全部值 取出特定的值 两种方法

    //第一种 Iterator menus = menu.iterator(); while(menus.hasNext()) { Map userMap = (Map) menus.next(); S ...

  5. HashMap如何做循环遍历

    1.TestCase:

  6. HashSet、HashMap、Hashtable、TreeMap循环、区别

    HashSet 循环 //可以为null HashSet<Object> hashSet =new HashSet<Object>(); hashSet.add(1); has ...

  7. ArrayList和LinkedList的几种循环遍历方式及性能对比分析(转)

    主要介绍ArrayList和LinkedList这两种list的五种循环遍历方式,各种方式的性能测试对比,根据ArrayList和LinkedList的源码实现分析性能结果,总结结论. 通过本文你可以 ...

  8. ArrayList和LinkedList的几种循环遍历方式及性能对比分析(转载)

    原文地址: http://www.trinea.cn/android/arraylist-linkedlist-loop-performance/ 原文地址: http://www.trinea.cn ...

  9. 【转】ArrayList和LinkedList的几种循环遍历方式及性能对比分析

    原文网址:http://www.trinea.cn/android/arraylist-linkedlist-loop-performance/ 主要介绍ArrayList和LinkedList这两种 ...

随机推荐

  1. 致命错误: Call to undefined function %y-%M-%d()

    在TP5.0中套模板时出现的问题: 原有html模板代码: <input type="text" onfocus="WdatePicker({ maxDate:'# ...

  2. IMU预积分

    https://www.sohu.com/a/242760307_715754 http://www.sohu.com/a/243155537_715754 https://www.sohu.com/ ...

  3. java 方法的定义与调用

    /* 定义一个方法的格式: public static void 方法名称(){ 方法体 } 方法名称的命名规则和变量一样,使用小驼峰 方法体:也就是大括号里面的可以包含任何语句 注意事项: 1.方法 ...

  4. day12 python函数名的应用 闭包 迭代器

    day12 python   一.函数名的应用(是第一类对象)     函数名的命名规范和变量是一样的     函数名其实就是变量名 def func():     print('i am funct ...

  5. java延迟队列

    大多数用到定时执行的功能都是用任务调度来做的,单身当碰到类似订餐业务/购物等这种业务就不好处理了,比如购物的订单功能,在你的订单管理中有N个订单,当订单超过十分钟未支付的时候自动释放购物车中的商品,订 ...

  6. 属性class与:class

    1.官方的案例 我们可以传给 v-bind:class 一个对象,以动态地切换 class <div v-bind:class="{ active: isActive }"& ...

  7. Django创建工程项目以及工作原理

    一.Django 创建工作项目 1.创建 North 工程项目 (1)使用CMD命令行,切换到指定路径 django-admin.py startproject north (2)使用pycharm创 ...

  8. webpack 学习1 安装构建项目

    本文中使用的webpack版本是4+,请注意区分 node.js安装 node.js下载地址 选择较低版本的稳定版下载,下载完成后得到的是一个msi文件,点击安装即可 安装完毕以后新建一个文件夹,并在 ...

  9. 重学JavaScript - 映射与集合

    作者:狐狸家的鱼 GitHub:surRimn 整理自MDN文档 带键的集合 映射 Map对象 一个Map对象在迭代时会根据对象中元素的插入顺序来进行 — 一个 for...of 循环在每次迭代后会返 ...

  10. Django学习笔记(三)视图

    构建网页内容 视图函数的return具有多种响应类型: 上述函数主要来自django.http,该模块是实现响应功能的核心. 实际开发中可用此模块实现文件下载功能,在index的urls.py和vie ...