HashMap两种遍历数据的方式
HashMap的遍历有两种方式,一种是entrySet的方式,另外一种是keySet的方式。
第一种利用entrySet的方式:
Map map = new HashMap();
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
}
上面的方式可以变化为for循环的形式:
Map<String, String> map = new HashMap<String, String>();
for (Entry<String, String> entry : map.entrySet()) {
entry.getKey();
entry.getValue();
}
第二种利用keySet的方式:
Map map = new HashMap();
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
Object key = iter.next();
Object val = map.get(key);
}
上面的方式也可以变化为for循环的形式:
Map<String, String> map = new HashMap<String, String>();
for (String key : map.keySet()) {
map.get(key);
}
这两种方式那种效率高呢?可以从下面的试验可以看出来:
public class Test
{
public static void main(String[] args)
{
HashMap<String, String> map = new HashMap<String, String>();
for (int i = 0; i < 1000000; i++)
{
map.put(i + "", "hello world");
}
long begin1 = System.currentTimeMillis();
Iterator iterator1 = map.entrySet().iterator();
while (iterator1.hasNext())
{
Map.Entry entry = (Map.Entry) iterator1.next();
Object key1 = entry.getKey();
Object val1 = entry.getValue();
}
long end1 = System.currentTimeMillis();
System.out.println("map.entrySet方式变量花费的时间为:" + (end1 - begin1));
long begin2 = System.currentTimeMillis();
Iterator iterator2 = map.keySet().iterator();
while (iterator2.hasNext())
{
Object key2 = iterator2.next();
Object val2 = map.get(key2);
}
long end2 = System.currentTimeMillis();
System.out.println("map.keySet方式变量花费的时间为:" + (end2 - begin2));
}
}
结论:
经过运行多次,我发现两者的运行时间相差不多,而且没有明确显示出那种变量方式更快一些。有的人可能会觉得第一种变量方式会快一些,因为他们觉
得:keySet方式其实是遍历了2次,一次是转为iterator,一次就从HashMap中取出key所对应的value,而entry方式只遍历了
一次,把key和value都放到了entry中,所以entry方式更快一些。
但是我觉得这种分析的方式比较主观,我们更应该从源码的角度去分析。首先看一下迭代器的源码:
keySet的迭代器:
private final class KeyIterator extends HashIterator<K> {
public K next() {
return nextEntry().getKey();
}
}
entrySet的迭代器:
private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
public Map.Entry<K,V> next() {
return nextEntry();
}
}
从上面我们可以看到只是返回值不同而已,父类相同,所以性能相差不多。下面我们再看一下get方法的源码:
public V get(Object key) {
if (key == null)
return getForNullKey();
Entry<K,V> entry = getEntry(key);
return null == entry ? null : entry.getValue();
}
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算法。所以两种性能差别不大。从上面的分析来看,我们得到最终的结论:
(1)HashMap的循环,如果既需要key也需要value,直接用下面的即可,foreach简洁易懂。
Map<String, String> map = new HashMap<String, String>();
for (Entry<String, String> entry : map.entrySet()) {
entry.getKey();
entry.getValue();
}
(2)如果只是遍历key而无需value的话,可以直接用下面的方式:
Map<String, String> map = new HashMap<String, String>();
for (String key : map.keySet()) {
// key process
}
原文地址:http://swiftlet.net/archives/1259
HashMap两种遍历数据的方式的更多相关文章
- HashMap两种遍历方式的深入研究
转自:http://swiftlet.net/archives/1259 HashMap的遍历有两种方式,如下所示:第一种利用entrySet的方式: 1 2 3 4 5 6 7 Map map ...
- Java HashMap两种遍历方式
第一种: Map map = new HashMap(); Iterator iter = map.entrySet().iterator(); while (iter.hasNext()) { Ma ...
- hashmap两种遍历方法
第一种:使用entryset来进行遍历 Map map=new HashMap(); Iterator iter=map.entrySet().iterator(); while(iter.hasNe ...
- HashMap的两种遍历方式
HashMap的两种遍历方式 HashMap存储的是键值对:key-value . java将HashMap的键值对作为一个整体对象(java.util.Map.Entry)进行处理,这优化了Hash ...
- Map的两种遍历方式
********************************************************************************* ****************** ...
- Request三种获取数据的方式
今天在做ajax请求后台代码时,发现ajax的方法都对,但就是请求不了后台代码,后来在同事帮助下才发现前台定义了两个相同参数导致请求出错. 下面记录一下request三种获取数据的方式: 1. Req ...
- 两种获取connectionString的方式
两种获取connectionString的方式 1. public static string connectionString = ConfigurationManager.ConnectionSt ...
- Java中有两种实现多线程的方式以及两种方式之间的区别
看到一个面试题.问两种实现多线程的方法.没事去网上找了找答案. 网上流传很广的是一个网上售票系统讲解.转发过来.已经不知道原文到底是出自哪里了. Java中有两种实现多线程的方式.一是直接继承Thre ...
- MYSQL 4种插入数据的方式比较
4种插入数据的方式 第一种:insert into insert into是最常用的插入数据的方式,可以单条插入,也可以多条,还可以指定从其他表中select然后插入. 详细可以参考:insert语法 ...
随机推荐
- 关于mac安装rails报错clang: error: unknown argument
文章都是从我的个人博客上转载过来的,大家可以点击我的个人博客. www.iwangzheng.com mac上安装rails的时候报错, 安装rails的在终端执行了一句命令: $sudo gem i ...
- 使用HTML5 Web存储的localStorage和sessionStorage方式
localStorage(本地存储),可以长期存储数据,没有时间限制,一天,一年,两年甚至更长,数据都可以使用.sessionStorage(会话存储),只有在浏览器被关闭之前使用,创建另一个页面时同 ...
- 在ubuntu 15.04下安装VMware Tools
提出问题:在Ubuntu 15. 04版本上,不能实现剪贴板的共享 解决方法:发现没有装VMware Tools 安装VMware Tools步骤 1. 点击菜单栏,虚拟机 → 安装VMware工具 ...
- Nmap备忘单:从探索到漏洞利用(Part 2)
这是我们的第二期NMAP备忘单(第一期在此).基本上,我们将讨论一些高级NMAP扫描的技术,我们将进行一个中间人攻击(MITM).现在,游戏开始了. TCP SYN扫描 SYN扫描是默认的且最流行的扫 ...
- nc 常用命令
nc(NetCat),在网络工具中有”瑞士军刀”的美誉,它短小精悍,功能强大,下面分享一些我平时经常用到的功能,更多的功能请google之. 1.基本参数想要连接到某处: nc [-options] ...
- Windows远程桌面连接如何直接使用剪贴板功能
连接到Windows Server服务器时,通常使用远程桌面连接,那么如果有些时候按照习惯复制本地文件到远程服务器发现无法粘贴怎么办,这个时候稍微设置一下就OK了, 首先重新运行远程桌面连接,在登陆界 ...
- zabbix_agent key 传递参数
root@(none):/etc/zabbix/zabbix_agentd.conf.d# pwd /etc/zabbix/zabbix_agentd.conf.d root@(none):/etc/ ...
- stsadm.exe
Usage: stsadm.exe -o <operation> [<parameters>] stsadm.exe -help [<operation>] Ope ...
- 二叉树学习笔记之二叉查找树(BSTree)
二叉查找树即搜索二叉树,或者二叉排序树(BSTree),学习回顾一下有关的知识. >>关于二叉查找树 二叉查找树(Binary Search Tree)是指一棵空树或者具有下列性质的二叉树 ...
- linux tricks 之VA系列函数.
VA函数(variable argument function),参数个数可变函数,又称可变参数函数.C/C++编程中,系统提供给编程人员的va函数很少.*printf()/*scanf()系列函数, ...