Java遍历Map四种方式讲解
Java中遍历Map的四种方式
在java中所有的map都实现了Map接口,因此所有的Map(如HashMap, TreeMap, LinkedHashMap, Hashtable等)都可以用以下的方式去遍历。
方法一:在for循环中使用entries实现Map的遍历:
/** * 最常见也是大多数情况下用的最多的,一般在键值对都需要使用 */ Map <String,String>map = new HashMap<String,String>(); map.put("熊大", "棕色"); map.put("熊二", "黄色"); for(Map.Entry<String, String> entry : map.entrySet()){ String mapKey = entry.getKey(); String mapValue = entry.getValue(); System.out.println(mapKey+":"+mapValue); }
方法二:在for循环中遍历key或者values,一般适用于只需要map中的key或者value时使用,在性能上比使用entrySet较好;
Map <String,String>map = new HashMap<String,String>(); map.put("熊大", "棕色"); map.put("熊二", "黄色"); //key for(String key : map.keySet()){ System.out.println(key); } //value for(String value : map.values()){ System.out.println(value); }
方法三:通过Iterator遍历;
Iterator<Entry<String, String>> entries = map.entrySet().iterator(); while(entries.hasNext()){ Entry<String, String> entry = entries.next(); String key = entry.getKey(); String value = entry.getValue(); System.out.println(key+":"+value); }
方法四:通过键找值遍历,这种方式的效率比较低,因为本身从键取值是耗时的操作;
for(String key : map.keySet()){ String value = map.get(key); System.out.println(key+":"+value); }
到此这篇关于Java遍历Map四种方式讲解的文章就介绍到这了,更多相关Java遍历Map内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringBoot数据库恢复的两种方法mysqldump和mysqlbinlog
binlog用来实现主从复制,也常用来误删数据库找回丢失的记录,本文主要介绍了SpringBoot数据库恢复的两种方法mysqldump和mysqlbinlog,具有一定的参考价值,感兴趣的可以了解一下2024-01-01微信小程序调用微信登陆获取openid及java做为服务端示例
这篇文章主要介绍了微信小程序调用微信登陆获取openid及java做为服务端示例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2018-01-01SpringBoot中@ConditionalOnProperty的使用及作用详解
这篇文章主要介绍了SpringBoot中@ConditionalOnProperty的使用及作用详解,@ConditionalOnProperty通过读取本地配置文件中的值来判断 某些 Bean 或者 配置类 是否加入spring 中,需要的朋友可以参考下2024-01-01
最新评论