哪种Map遍历方法更优?!—Map遍历方法的正确选择

我们都知道遍历Map一般有3种方法,values(),keySet()和entrySet(),常见的是keySet用的多,简单容易理解,entrySet()是返回Map中的静态内部类Entry类类型的Set实例,当然了你别说forEach,forEach只是一种代替for(int i=0;;)和while()遍历的一种方式,底层也是用迭代器实现的,只不过把部分东西隐藏了,建议大家平常开发中能用forEach遍历,尽可能的用这个,《Effective java》中也明确表示了,简单而不容易出错。
如果Map中有大量的元素,而且并发量又很高,这就涉及到采用哪种遍历方法的问题,下面就来测试一下:

[java]  view plain  copy
  1.               Map<String,String> mapTest=new HashMap<String,String>();  
  2. for(int i=0;i<10000;i++){  
  3.     mapTest.put(String.valueOf(i),String.valueOf(i) );  
  4. }  
  5.   
  6. //一种遍历,keySet()方法  
  7. long start=System.nanoTime();  
  8. Set<String> setEach=mapTest.keySet();  
  9. for(String key:setEach){  
  10.     String value=mapTest.get(key);  
  11. }  
  12. long end=System.nanoTime();  
  13. System.out.println("keySet遍历map耗时"+(end-start)/1000+"微秒");  
[java]  view plain  copy
  1.               //二种遍历,可用values()返回Collection<T>,不容易得到对应的key  
  2. start=System.nanoTime();  
  3. Collection<String> co=mapTest.values();  
  4. for(String value:co){  
  5.     //遍历中也在创建value  
  6. }  
  7. end=System.nanoTime();  
  8. System.out.println("values遍历map(只得到值)耗时"+(end-start)/1000+"微秒");  
[java]  view plain  copy
  1. //三种遍历,用entrySet()方法返回Set<Map.Entry<T,T>>类型,再获取里边的Map.Entry  
  2. start=System.nanoTime();  
  3. Set<Map.Entry<String,String>> entrySet=mapTest.entrySet();  
  4. for(Map.Entry<String, String> entry:entrySet){  
  5.     String key=entry.getKey();  
  6.     String value=entry.getValue();  
  7. }  
  8. end=System.nanoTime();  
  9. System.out.println("entrySet遍历map耗时"+(end-start)/1000+"微秒");  

经过多次运行,结果大概都是这样的:

[java]  view plain  copy
  1. keySet遍历map耗时9867微秒  
  2. values遍历map(只得到值)耗时2539微秒  
  3. entrySet遍历map耗时2783微秒  

 

 

       values()是返回Map的所有value的集合collection,只能遍历到值,很难遍历到key所以一般不用,除非在某种特殊场合,所以一般采用的第一种和第三种方式。而测试表明entrySet()方式遍历效率更高。
       entrySet()方式遍历之所以快与keySet(),一个原因是keySet相当与遍历了2次,一次是对key的Set集合的遍历,二次是每次遍历过程都要通过key和map.get(key)来获取value值。第二个原因是map.get(key)获取的时候,底层其实根据key的hashcode值经过哈希算法得到一个hash值然后作为索引映射到对应table数组的索引位置,这是一次密集型计算,很耗费CPU,如果有大量的元素,则会使CPU使用率飙升,影响响应速度,而entrySet()返回的set里边元素都是Map.Entry类型,key和value就是这个类的一个属性,entry.getKey()和entry.getValue()效率肯定很高。
       所以平常开发过程中,如果对Map讲究效率的遍历的话,还是采用entrySet()方法。

转载请注明—作者:Java我人生(陈磊兴)   原文出处:http://blog.csdn.net/chenleixing/article/details/44087131

猜你喜欢

转载自blog.csdn.net/liaodehong/article/details/78637530