博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java中如何遍历Map对象的4种方法
阅读量:6948 次
发布时间:2019-06-27

本文共 3792 字,大约阅读时间需要 12 分钟。

在Java中如何遍历Map对象

How to Iterate Over a Map in Java

在java中遍历Map有不少的方法。我们看一下最常用的方法及其优缺点。

既然java中的所有map都实现了Map接口,以下方法适用于任何map实现(HashMap, TreeMap, LinkedHashMap, Hashtable, 等等)

 

方法一 在for-each循环中使用entries来遍历

这是最常见的并且在大多数情况下也是最可取的遍历方式。在键值都需要时使用。

Class : 

        /**             * 在for-each循环中使用entries来遍历             */            Map
map = new HashMap
(); map.put("lime", new User(1, "lime", 23)); map.put("oracle", new User(2, "oracle", 34)); for (Entry
entry : map.entrySet()) { System.out.println("key : " + entry.getKey() + " | value : " + entry.getValue()); } /** * 如果你遍历的是一个空的map对象,for-each循环将抛出NullPointerException, * 因此在遍历前你总是应该检查空引用。 */ map.clear(); map.put("lime", null); for (Entry
entry : map.entrySet()) { System.out.println("key : " + entry.getKey() + " | value : " + entry.getValue()); }

Console : 

key : lime | value : User [id=1, name=lime, age=23]key : oracle | value : User [id=2, name=oracle, age=34]key : lime | value : null

注意:for-each循环在5中被引入所以该方法只能应用于java 5或更高的版本中。如果你遍历的是一个空的map对象,for-each循环将抛出NullPointerException,因此在遍历前你总是应该检查空引用。

方法二 在for-each循环中遍历keys或values。

如果只需要map中的键或者值,你可以通过keySet或values来实现遍历,而不是用entrySet。

Class : 

/**             * 在for-each循环中遍历keys或values。             */            Map
map = new HashMap
(); map.put("lime", new User(1, "lime", 23)); map.put("oracle", new User(2, "oracle", 34)); /** * 如果只需要map中的键或者值,你可以通过keySet或values来实现遍历,而不是用entrySet。 */ for (String key : map.keySet()) { System.out.println("key : " + key); } for (User user : map.values()) { System.out.println("user : " + user); }

Console : 

key : limekey : oracleuser : User [id=1, name=lime, age=23]user : User [id=2, name=oracle, age=34]

该方法比entrySet遍历在性能上稍好(快了10%),而且代码更加干净。

 

方法三使用Iterator遍历

Class : 

        /**             * 使用Iterator遍历:使用泛型             */            Map
map = new HashMap
(); map.put("lime", new User(1, "lime", 23)); map.put("oracle", new User(2, "oracle", 34)); Iterator
> iterator = map.entrySet().iterator(); while(iterator.hasNext()){ Map.Entry
entry = iterator.next(); System.out.println("key : " + entry.getKey() + " | Value : " + entry.getValue()); }

Console :

key : lime | Value : User [id=1, name=lime, age=23]key : oracle | Value : User [id=2, name=oracle, age=34]

你也可以在keySet和values上应用同样的方法。

该种方式看起来冗余却有其优点所在。首先,在老版本java中这是惟一遍历map的方式。另一个好处是,你可以在遍历时调用iterator.remove()来删除entries,另两个方法则不能。根据javadoc的说明,如果在for-each遍历中尝试使用此方法,结果是不可预测的。

从性能方面看,该方法类同于for-each遍历(即方法二)的性能。

方法四、通过键找值遍历(效率低)

Class : 

        /**             * 通过键找值遍历(效率低)             */            Map
map = new HashMap
(); map.put("lime", new User(1, "lime", 23)); map.put("oracle", new User(2, "oracle", 34)); for(String key : map.keySet()){ System.out.println("key : " + key + " | value : " + map.get(key)); }

Console : 

key : lime | value : User [id=1, name=lime, age=23]key : oracle | value : User [id=2, name=oracle, age=34]

作为方法一的替代,这个代码看上去更加干净;但实际上它相当慢且无效率。因为从键取值是耗时的操作(与方法一相比,在不同的Map实现中该方法慢了20%~200%)。如果你安装了FindBugs,它会做出检查并警告你关于哪些是低效率的遍历。所以尽量避免使用。

 

总结

如果仅需要键(keys)或值(values)使用方法二。如果你使用的语言版本低于java 5,或是打算在遍历时删除entries,必须使用方法三。否则使用方法一(键值都要)。

啦啦啦

转载地址:http://mhhnl.baihongyu.com/

你可能感兴趣的文章
Android Studio第三十期 - 介绍几种网络请求方式写法
查看>>
计划任务导致的邮件系统故障
查看>>
《从零开始学Swift》学习笔记(Day 35)——会使用下标吗?
查看>>
盛大私有化和陈天桥的土皇帝心态
查看>>
Exchange Server 2013 公网发布疑难解答
查看>>
Oracle 12c dataguard云上挖坑记--为某机场贵宾业务部署oracle 12c到云端
查看>>
前端开发在不久的将来定会成为主导
查看>>
jQuery内ready与load事件的区别
查看>>
[笔记].关于Stratix III使用非易失加密后,无法正常配置启动的问题探讨
查看>>
一个通用的单元测试框架的思考和设计03-实现篇-核心类源码
查看>>
万能导出数据到Excel
查看>>
[感谢坑娘][回忆3年前]茜色的终点线....
查看>>
减少垃圾广告 让你的电子邮箱更安全
查看>>
载入史册 改变IT安全历程的十大里程碑
查看>>
UVA 624 CD
查看>>
Windows phone 7: DataBinding and UI Refresh系列教程
查看>>
矩阵快速幂 学习笔记
查看>>
linux iconv 批量转码
查看>>
使用MongoDB的GridFS保存用户文件的折腾日记
查看>>
Linux的Find使用
查看>>