Java中Map遍历常用的四种方法
来源:互联网 发布:新技术网络 编辑:程序博客网 时间:2024/05/21 09:06
今天写程序又用到了HashMap(),在此我也总结一下,自己以前用过的四种方法。
package com.xing.test;import java.util.HashMap;import java.util.Iterator;import java.util.Map;/** * * @author Yinxing * */public class OutMap {public static void main(String[] args) {Map<String, String> map = new HashMap<String, String>();map.put("1", "烟台大学");map.put("2", "清华大学");map.put("3", "北京大学");// 第一种:普遍使用,二次取值System.out.println("通过Map.keySet遍历key和value:");for (String key : map.keySet()) {System.out.println("key= " + key + " and value= " + map.get(key));}// 第二种:效率要高一些System.out.println("通过Map.entrySet使用iterator遍历key和value:");Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();while (it.hasNext()) {Map.Entry<String, String> entry = it.next();System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());}// 第三种:适合容量大时System.out.println("通过Map.entrySet遍历key和value");for (Map.Entry<String, String> entry : map.entrySet()) {System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());}// 第四种System.out.println("通过Map.values()遍历所有的value,但不能遍历key");for (String v : map.values()) {System.out.println("value= " + v);}}}一般来讲,采用entryset来遍历的话效率要高一些。原因在于hashMap内部的存储结构使用的是Entry<key,value>的数组,Entry对象里面直接包含了key和value,用entrySet的方式,只需要把数组遍历一遍,而用keySet的方式,每次都要通过key去计算hash,然后再通过hash获得value,相当于多了一次get(key),所以效率较低。
0 0
- Java中Map遍历常用的四种方法
- Java中Map遍历常用的四种方法
- java 中map遍历的四种方法和优缺点
- java中遍历map对象的四种方法
- Java中,Map遍历的四种方法
- java中遍历map的四种方法
- Java中遍历Map的四种方法
- java中 遍历 map 的 四种方法
- Java中遍历Map的四种方法总结
- Java中遍历map的四种方法
- java Map 遍历的四种方法
- java 遍历Map的四种方法
- java遍历Map的四种方法
- java 遍历Map的四种方法
- Java 遍历Map的四种方法
- JAVA 遍历Map的四种方法
- Java遍历Map的四种方法
- java 遍历Map的四种方法
- louboutin He Guiyan
- 从零开始
- NSTimer实现连续帧动画播放
- cheap toms outlet Tung Chung
- 病毒
- Java中Map遍历常用的四种方法
- TCP/IP详解学习笔记(11)-TCP交互数据流,成块数据流
- Android环境搭建——adt无法更新或者无法在线安装的解决方法
- db 笔记本
- codeforce 7C &&拓展欧几里得 详解
- Windows 剪切板相关API说明
- oracle job 定时执行 存储过程
- Codeforces Round #264 (Div. 2) | ABCD
- 对自己狠一点,离成功近一点