java HashMap遍历的三种方式以及效率对比

来源:互联网 发布:lg笔记本怎么样知乎 编辑:程序博客网 时间:2024/05/16 08:32


java HashMap遍历的三种方式以及效率对比

/* HashMap */public static void hashMap(){Map<String,String> hashMap = new HashMap<String, String>();for(int i=0;i<100000;i++)hashMap.put(i+"", i+"v");long time = System.currentTimeMillis();System.out.println("==============方式1:通过遍历keySet()遍历HashMap的value");Iterator<String> it = hashMap.keySet().iterator();while(it.hasNext()){hashMap.get(it.next());//System.out.println(hashMap.get(it.next()));}System.out.println("用时:"+(System.currentTimeMillis() - time));time = System.currentTimeMillis();System.out.println("==============方式2:通过遍历values()遍历HashMap的value");Collection<String> values = hashMap.values();for(Iterator<String> valIt = values.iterator();valIt.hasNext();){valIt.next();}System.out.println("用时:"+(System.currentTimeMillis() - time));time = System.currentTimeMillis();System.out.println("==============方式3:通过entrySet().iterator()遍历HashMap的key和映射的value");Iterator<Entry<String, String>> entryIt = hashMap.entrySet().iterator();while(entryIt.hasNext()){Entry<String, String> entry = entryIt.next();entry.getKey();entry.getValue();//System.out.println("key:"+entry.getKey()+" value:"+entry.getValue());}System.out.println("用时:"+(System.currentTimeMillis() - time));}

以上代码运行结果如下:
==============方式1:通过遍历keySet()遍历HashMap的value
用时:61
==============方式2:通过遍历values()遍历HashMap的value
用时:7
==============方式3:通过entrySet().iterator()遍历HashMap的key和映射的value
用时:12

第一种方式是遍历key,根据key获取映射的vlaue,需要调用get()方法十万次,肯定是效率不高的。建议在数据量较大时不用此方式遍历hashMap。
第二种方式是获取集合中的values,遍历value。但是在遍历value的时候,获取不到key。建议在只需要获取集合中的value时使用此方式。
第三种方式是获取Entry<K,V>类型的Set集合,遍历这个集合,获取每一个Entry<K,V>,通过getKey()和getValue来获取key和value。Entry<K,V>是HashMap集合中的键值对。这样就就相当于遍历了一遍HashMap中的键值对 。
省去了第一种方式中get()的操作。建议多用此方式来遍历hashMap结合。
public Set<K> keySet() 方法返回值是Map中key值的集合;public Set<Map.Entry<K,V>>  entrySet()方法返回值也是返回一个Set集合,此集合的类型为Map.Entry。
Map.Entry是Map声明的一个内部接口,此接口为泛型,定义为Entry<K,V>。它表示Map中的一个实体(一个key-value对)。接口中有getKey(),getValue方法。
HashMap是这样,换成TreeMap道理也一样。
在来说一下Map.Entry接口的使用场合:
因为Map这个类没有继承Iterable接口所以不能直接通过map.iterator来遍历(list,set就是实现了这个接口,所以可以直接这样遍历),所以就只能先转化为set类型,用entrySet()方法,其中set中的每一个元素值就是map中的一个键值对,也就是Map.Entry<K,V>了,然后就可以遍历了。
基本上 就是遍历map的时候才用得着它吧。





0 0
原创粉丝点击