我们都知道遍历Map一般有3种方法,values(),keySet()和entrySet(),常见的是keySet用的多,简单容易理解,entrySet()是返回Map中的静态内部类Entry类类型的Set实例,当然了你别说forEach,forEach只是一种代替for(int i=0;;)和while()遍历的一种方式,底层也是用迭代器实现的,只不过把部分东西隐藏了,建议大家平常开发中能用forEach遍历,尽可能的用这个,《Effective java》中也明确表示了,简单而不容易出错。
如果Map中有大量的元素,而且并发量又很高,这就涉及到采用哪种遍历方法的问题,下面就来测试一下:
Map mapTest=new HashMap(); for(int i=0;i<10000;i++){ maptest.put(string.valueof(i),string.valueof(i)="" );="" }="" 一种遍历,keyset()方法="" long="" start="System.nanoTime();">10000;i++){> setEach=mapTest.keySet(); for(String key:setEach){ String value=mapTest.get(key); } long end=System.nanoTime(); System.out.println('keySet遍历map耗时'+(end-start)/1000+'微秒');
//二种遍历,可用values()返回Collection,不容易得到对应的key start=System.nanoTime(); Collection co=mapTest.values(); for(String value:co){ //遍历中也在创建value } end=System.nanoTime(); System.out.println('values遍历map(只得到值)耗时'+(end-start)/1000+'微秒');
//三种遍历,用entrySet()方法返回Set<>>类型,再获取里边的Map.Entry start=System.nanoTime(); Set<>> entrySet=mapTest.entrySet(); for(Map.Entry entry:entrySet){ String key=entry.getKey(); String value=entry.getValue(); } end=System.nanoTime(); System.out.println('entrySet遍历map耗时'+(end-start)/1000+'微秒');
经过多次运行,结果大概都是这样的:
keySet遍历map耗时9867微秒values遍历map(只得到值)耗时2539微秒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
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。