您的位置:首页 > 编程语言 > Java开发

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循环的加入简化了集合的遍历。

  //其语法如下:
  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遍历。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: