网站首页 > java教程 正文
本文实例讲述了Java HashMap三种循环遍历方式及其性能对比。分享给大家供大家参考,具体如下:
HashMap的三种遍历方式

(1)for each map.entrySet()
Map<String, String> map = new HashMap<String, String>();
for (Entry<String, String> entry : map.entrySet()) {
  entry.getKey();
  entry.getValue();
}
(2)显示调用map.entrySet()的集合迭代器
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
  entry.getKey();
  entry.getValue();
}
(3)for each map.keySet(),再调用get获取
Map<String, String> map = new HashMap<String, String>();
for (String key : map.keySet()) {
  map.get(key);
}
三种遍历方式的性能测试及对比
测试环境:Windows7 32位系统 3.2G双核CPU 4G内存,Java 7,Eclipse -Xms512m -Xmx512m
测试结果:
遍历方式结果分析
由上表可知:
- for each entrySet与for iterator entrySet性能等价
 - for each keySet由于要再调用get(key)获取值,比较耗时(若hash散列算法较差,会更加耗时)
 - 在循环过程中若要对map进行删除操作,只能用for iterator entrySet(在HahsMap非线程安全里介绍)。
 
HashMap entrySet源码
public V get(Object key) {
  if (key == null)
    return getForNullKey();
  Entry<K,V> entry = getEntry(key);
  return null == entry ? null : entry.getValue();
}
/**
 1. Returns the entry associated with the specified key in the
 2. HashMap. Returns null if the HashMap contains no mapping
 3. 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;
}
结论
- 循环中需要key、value,但不对map进行删除操作,使用for each entrySet
 - 循环中需要key、value,且要对map进行删除操作,使用for iterator entrySet
 - 循环中只需要key,使用for each keySet
 
猜你喜欢
- 2024-10-26 Java8 List转Map,我卡壳了......
 - 2024-10-26 HashMap 的 7 种遍历方式与性能分析!(强烈推荐)
 - 2024-10-26 Java集合-- Map(Java集合类)
 - 2024-10-26 js 函数式编程:不要再使用 for 循环啦,试试 map 吧
 - 2024-10-26 大厂Java二面:Spring循环依赖,烂大街的问题这么答面试官才满意
 - 2024-10-26 JAVA集合之 MAP和HASHMAP(java中map和hashmap)
 - 2024-10-26 双列集合Map不再难懂:轻松掌握这些知识点!
 - 2024-10-26 用到停不下来,Java 8 新特性:foreach 和 stream
 - 2024-10-26 Go语言开发者必知必会的Map优化技巧
 - 2024-10-26 计算机程序员的入门实践-Map常用的遍历方式(七)
 
欢迎 你 发表评论:
- 最近发表
 
- 标签列表
 - 
- java反编译工具 (77)
 - java反射 (57)
 - java接口 (61)
 - java随机数 (63)
 - java7下载 (59)
 - java数据结构 (61)
 - java 三目运算符 (65)
 - java对象转map (63)
 - Java继承 (69)
 - java字符串替换 (60)
 - 快速排序java (59)
 - java并发编程 (58)
 - java api文档 (60)
 - centos安装java (57)
 - java调用webservice接口 (61)
 - java深拷贝 (61)
 - 工厂模式java (59)
 - java代理模式 (59)
 - java.lang (57)
 - java连接mysql数据库 (67)
 - java重载 (68)
 - java 循环语句 (66)
 - java反序列化 (58)
 - java时间函数 (60)
 - java是值传递还是引用传递 (62)
 
 

本文暂时没有评论,来添加一个吧(●'◡'●)