两种方式遍历HashMap

来源:互联网 发布:图像坐标轴 知乎 编辑:程序博客网 时间:2024/05/17 03:01

通过Map类的get(key)方法获取value时,会进行两次hashCode的计算,消耗CPU资源;而使用entrySet的方式,map对象会直接返回其保存key-value的原始数据结构对象,遍历过程无需进行错误代码中耗费时间的hashCode计算; 这在大数据量下,体现的尤为明显。

[java] view plaincopy
  1. package com.bb.eoa.extend.yssp.controller;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.Iterator;  
  5. import java.util.Map;  
  6. import java.util.Set;  
  7.   
  8. public class T {  
  9.     public static void main(String[] args) {  
  10.         Map<String, String> map = new HashMap<String, String>();  
  11.         map.put("str1""str11");  
  12.         map.put("str2""str22");  
  13.         map.put("str3""str33");  
  14.         /** 
  15.          * 第一种方式:通过Map类的get(key)方法获取value 
  16.          */  
  17.   
  18.         for (Iterator<String> ite = map.keySet().iterator(); ite.hasNext();) { // foreach输出  
  19.             Object key = ite.next();  
  20.             Object value = map.get(key);  
  21.             System.out.print(key);  
  22.             System.out.print("-->");  
  23.             System.out.print(value);  
  24.             System.out.println();  
  25.         }  
  26.   
  27.         System.out.println("-----------");  
  28.   
  29.         Set s = map.keySet(); // 普通方式输出  
  30.         Iterator i = s.iterator();  
  31.         while (i.hasNext()) {  
  32.             Object key = i.next();  
  33.             Object value = map.get(key);  
  34.             System.out.print(key);  
  35.             System.out.print("-->");  
  36.             System.out.print(value);  
  37.             System.out.println();  
  38.         }  
  39.         System.out.println("---------");  
  40.         /** 
  41.          * 第二种方式:利用entrySet方式,map对象会直接返回其保存key-value的原始数据结构对象 
  42.          */  
  43.         Set entry = map.entrySet();   //普通方式输出  
  44.         Iterator ite = entry.iterator();  
  45.         while (ite.hasNext()) {  
  46.             Map.Entry m = (Map.Entry) ite.next(); // Set中的每一个元素都是Map.Entry  
  47.             System.out.print(m.getKey() + "-->");  
  48.             System.out.println(m.getValue());  
  49.         }  
  50.         System.out.println("-----------");   
  51.         for (Iterator it = map.entrySet().iterator(); it.hasNext();) { // foreach输出  
  52.             Map.Entry e = (Map.Entry) it.next();  
  53.             System.out.print(e.getKey()+"-->");  
  54.             System.out.print(e.getValue());  
  55.             System.out.println();  
  56.         }     
  57.     }  
  58. }  
0 0
原创粉丝点击