`
jianweicao
  • 浏览: 116801 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

java遍历map方法

 
阅读更多

java 代码:

  • import java.util.HashMap;   
  • import java.util.Iterator;   
  • import java.util.Map;   
  •   
  • public class MapTest {   
  •   
  •     public static void main(String[] args) {   
  •         Map<String, String> map = new HashMap<String, String>();   
  •         map.put("1""1");   
  •         map.put("2""2");   
  •         map.put("3""3");   
  •   
  •   
  •         // 第一种:通过Map.keySet遍历key和value   
  •         System.out.println("通过Map.keySet遍历key和value:");   
  •         for (String key : map.keySet()) {   
  •             System.out.println("key= " + key + "  and  value= " + map.get(key));   
  •         }   
  •            
  •         // 第二种:通过Map.entrySet使用iterator遍历key和value   
  •         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());   
  •         }   
  •   
  •         // 第三种:通过Map.entrySet遍历key和value   
  •         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());   
  •         }   
  •   
  •         // 第四种:通过Map.values()遍历所有的value,但是不能遍历键key   
  •         System.out.println("通过Map.values()遍历所有的value:");   
  •         for (String v : map.values()) {   
  •             System.out.println("value= " + v);   
  •         }   
  •     }   
  •   
  • }  
  • 结果
  • 通过Map.keySet遍历key和value:   
  • key= 3  and  value= 3  
  • key= 2  and  value= 2  
  • key= 1  and  value= 1  
  • 通过Map.entrySet使用iterator遍历key和value:   
  • key= 3  and  value= 3  
  • key= 2  and  value= 2  
  • key= 1  and  value= 1  
  • 通过Map.entrySet遍历key和value:   
  • key= 3  and  value= 3  
  • key= 2  and  value= 2  
  • key= 1  and  value= 1  
  • 通过Map.values()遍历所有的value:   
  • value= 3  
  • value= 2  
  • value= 1 

    这四种方法都可以遍历map:

    第一种是目前许多人最喜欢的一种方式,因为代码最少,看起来最简单,通过遍历keySet,再将key所对应的value查询出来,这里有一个二次取值的过程,所以并不推荐;

    第二种和第三种原理是相同的,都是通过遍历Map.Entry的方式,将Entry中的key和value打印出来,第三种是比较推荐写法,因为采用jdk1.5后的遍历形式,代码看起来比较整洁;

    第四种比较少用,因为我们大多数时候都是同时需要key和value的

     

    综上所述,如果map里面内容比较少,其实采用哪种方式都可以,第一种和第三种相对简洁一些;但是一旦容量非常大时,更推荐采用第三种方式,相比于第一种将极大地节省性能。

     

    修改一下代码,对执行时间执行一下测试

     

    Java代码
    1. import java.util.HashMap;   
    2. import java.util.Map;   
    3.   
    4. public class MapTest {   
    5.     static long MAX_LONG = 1000000L;   
    6.     static int TIMES = 10;   
    7.     static Map<String, String> map1 = new HashMap<String, String>();   
    8.     static Map<String, String> map2 = new HashMap<String, String>();   
    9.     static {   
    10.         for (long i = 0; i < MAX_LONG; i++) {   
    11.             map1.put("1" + i, "abc" + i);   
    12.             map2.put("2" + i, "def" + i);   
    13.         }   
    14.     }   
    15.   
    16.     public static void main(String[] args) {   
    17.   
    18.         String valueStr = "";    
    19.         String keyStr = "";   
    20.         long start, end;   
    21.         double totalMs;   
    22.   
    23.   
    24.   
    25.         totalMs = 0;   
    26.         for (int i = 0; i < TIMES; i++) {   
    27.   
    28.             // 通过Map.keySet遍历key和value   
    29.             start = System.currentTimeMillis();   
    30.             for (String key : map1.keySet()) {   
    31.                 keyStr = key;   
    32.                 valueStr = map1.get(key);   
    33.             }   
    34.             end = System.currentTimeMillis();   
    35.             System.out.println("通过Map.keySet遍历key和value耗时 " + (end - start)   
    36.                     + " ms ");   
    37.             totalMs += (end - start);   
    38.         }   
    39.         System.out.println("Times : " + TIMES + ", totalMs : " + totalMs   
    40.                 + "ms, average :" + totalMs / TIMES + "ms");   
    1.     }   
    2.   
    3. [java] view plaincopy
       
      1.    

     以下是测试结果:

    Java代码
    1. 通过Map.keySet遍历key和value耗时 186 ms    
    2. 通过Map.keySet遍历key和value耗时 189 ms    
    3. 通过Map.keySet遍历key和value耗时 87 ms    
    4. 通过Map.keySet遍历key和value耗时 89 ms    
    5. 通过Map.keySet遍历key和value耗时 84 ms    
    6. 通过Map.keySet遍历key和value耗时 92 ms    
    7. 通过Map.keySet遍历key和value耗时 85 ms    
    8. 通过Map.keySet遍历key和value耗时 94 ms    
    9. 通过Map.keySet遍历key和value耗时 89 ms    
    10. 通过Map.keySet遍历key和value耗时 91 ms    
    11. Times : 10, totalMs : 1086.0ms, average :108.6ms   
    12. 通过Map.entrySet遍历key和value耗时 112 ms    
    13. 通过Map.entrySet遍历key和value耗时 98 ms    
    14. 通过Map.entrySet遍历key和value耗时 71 ms    
    15. 通过Map.entrySet遍历key和value耗时 65 ms    
    16. 通过Map.entrySet遍历key和value耗时 65 ms    
    17. 通过Map.entrySet遍历key和value耗时 64 ms    
    18. 通过Map.entrySet遍历key和value耗时 64 ms    
    19. 通过Map.entrySet遍历key和value耗时 65 ms    
    20. 通过Map.entrySet遍历key和value耗时 65 ms    
    21. 通过Map.entrySet遍历key和value耗时 65 ms    
    22. Times : 10, totalMs : 734.0ms, average :73.4ms  
      [java] view plaincopy
       
      1.    
       可以看出,百万级别的量时,使用keySet和entrySet遍历,执行时间大概为1.5:1,这并不是最主要的差异。真正的差异还是必须看代码
    Java代码
    1. map.get(key))  
    [java] view plaincopy
     
    1. map.get(key))  

    时执行的hash操作

    Java代码
    1. /**  
    2.  * Returns the value to which the specified key is mapped,  
    3.  * or {@code null} if this map contains no mapping for the key.  
    4.  *  
    5.  * <p>More formally, if this map contains a mapping from a key  
    6.  * {@code k} to a value {@code v} such that {@code (key==null ? k==null :  
    7.  * key.equals(k))}, then this method returns {@code v}; otherwise  
    8.  * it returns {@code null}.  (There can be at most one such mapping.)  
    9.  *  
    10.  * <p>A return value of {@code null} does not <i>necessarily</i>  
    11.  * indicate that the map contains no mapping for the key; it's also  
    12.  * possible that the map explicitly maps the key to {@code null}.  
    13.  * The {@link #containsKey containsKey} operation may be used to  
    14.  * distinguish these two cases.  
    15.  *  
    16.  * @see #put(Object, Object)  
    17.  */  
    18. public V get(Object key) {   
    19.     if (key == null)   
    20.         return getForNullKey();   
    21.     int hash = hash(key.hashCode());   
    22.     for (Entry<K,V> e = table[indexFor(hash, table.length)];   
    23.          e != null;   
    24.          e = e.next) {   
    25.         Object k;   
    26.         if (e.hash == hash && ((k = e.key) == key || key.equals(k)))   
    27.             return e.value;   
    28.     }   
    29.     return null;   
    30. }   

    计算hashCode是CPU密集运算,非常耗费CPU资源,如果对一个比较大的map进行遍历,会出现CPU迅速飚高的现象,直接影响机器的响应速度,在多线程的情况下,简直就是一场灾难,而采用entrySet来进行遍历,则无此问题,对这个有兴趣的同学,可以使用自己的机器试一试。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics