Java Map 遍历的方法
2015-09-10 16:04
411 查看
Map 包括HashMap,TreeMap和LinkedHashMap等。
常用遍历的3种方法
Iterator JDK 1.4之前所用的遍历方法
JDK 1.5 之后引进,在for-each 循环使用entryset或者keySet或者values 来遍历
传统的for循环,使用hashmap keySet() 或者values来遍历
效率:
方法二优于方法一,方法一优于方法三
For-Each循环
For-Each循环也叫增强型的for循环,或者叫foreach循环。
For-Each循环是JDK5.0的新特性(其他新特性比如泛型、自动装箱等)。
For-Each循环的加入简化了集合的遍历。
参考
http://blog.csdn.net/tjcyjd/article/details/11111401
这篇文章最后一种的遍历方式例子写的还是for each遍历。
常用遍历的3种方法
Iterator JDK 1.4之前所用的遍历方法
JDK 1.5 之后引进,在for-each 循环使用entryset或者keySet或者values 来遍历
传统的for循环,使用hashmap keySet() 或者values来遍历
效率:
方法二优于方法一,方法一优于方法三
For-Each循环
For-Each循环也叫增强型的for循环,或者叫foreach循环。
For-Each循环是JDK5.0的新特性(其他新特性比如泛型、自动装箱等)。
For-Each循环的加入简化了集合的遍历。
//其语法如下: for(type element: array) { System.out.println(element); }
import java.util.HashMap; import java.util.Iterator; import java.util.Map; //Map各种遍历方法和效率的小结 public class MapTest { public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); for (int i = 1; i < 1000000; i++) { map.put(String.valueOf(i), String.valueOf(i)); } long start = 0L; long end = 0L; //方法 一 jdk 1.4 start = System.currentTimeMillis(); Iterator<Map.Entry<String, String>> iter = map.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = iter.next(); // System.out.println("\nkey:" + entry.getKey() + "\n value:" + entry.getValue()); } end = System.currentTimeMillis(); System.out.print("第一种方法运行时间:" + (end - start) + "(毫秒)\n"); // 方法二 JDK1.5中,应用新特性For-Each循环 start = System.currentTimeMillis(); for (Map.Entry<String, String> entry2 : map.entrySet()) { // System.out.println("\nkey:" + entry2.getKey() + "\n value:" + entry2.getValue()); } end = System.currentTimeMillis(); System.out.print("第二种方法运行时间:" + (end - start) + "(毫秒)\n"); // 方法三 hashmap keySet()或者values 遍历 start = System.currentTimeMillis(); for (String key : map.keySet()) { // System.out.println("\nkey:" + key + "\n value:" + value); } end = System.currentTimeMillis(); System.out.print("第三种方法运行时间:" + (end - start) + "(毫秒)\n"); // 方法四 hashmap keySet()或者values 遍历 start = System.currentTimeMillis(); for (Iterator it = map.keySet().iterator(); it.hasNext();) { String key = (String) it.next(); String value = map.get(key); // System.out.println("\nkey:" + key + "\n value:" + value); } end = System.currentTimeMillis(); System.out.print("第四种方法运行时间:" + (end - start) + "(毫秒)\n"); } } //最终运行的结果: 第一种方法运行时间:30(毫秒) 第二种方法运行时间:20(毫秒) 第三种方法运行时间:31(毫秒) 第四种方法运行时间:50(毫秒)
参考
http://blog.csdn.net/tjcyjd/article/details/11111401
这篇文章最后一种的遍历方式例子写的还是for each遍历。
相关文章推荐
- 第六章 访问权限控制
- Java对日期的处理
- Eclipse Hibernate 入门小程序
- Spring boot初探
- Java中的static关键字
- maven与springMVC之接收form表单防止乱码
- Win7下Eclipse中文字体太小
- java 笔记
- 【Java.Core】Java Date Time 教程
- Java IO
- java多线程通信之共享数据
- Java反射
- java删除文件和文件夹
- session原理解析
- JDK1.8 中的hashmap和concurrentHashMap
- java字符串池 引号创建与new String()创建字符串对象是不同的
- eclipse最佳设置
- Struts2的namespace问题探讨
- JDK篇
- 重拾java系列一java基础(2)