java中HashMap的遍历

来源:互联网 发布:玫瑰花 简笔画软件 编辑:程序博客网 时间:2024/06/01 08:21

在学习java时了解了java中HashMap的两种遍历方法,现总结如下:

<span style="white-space:pre"></span>HashMap<String,String> map;map = new HashMap<String, String>();for(int i=0;i<10000;i++){map.put("name"+i,"Name"+i);map.put("sex"+i, "男");map.put("grade"+i, "computer"+i);}/** * 遍历hashMap的第一种方法 */Iterator it = map.entrySet().iterator();/** * 记录开始时间 */long time11=Calendar.getInstance().getTimeInMillis();while(it.hasNext()){Map.Entry emtry = (Map.Entry) it.next();Object key = emtry.getKey();Object value = emtry.getValue();System.out.println(key+":"+value);}/** * 记录结束时间 */long time12 = Calendar.getInstance().getTimeInMillis();/** * 遍历HashMap的第二种方法 */System.out.println("====================");Iterator it1 = map.keySet().iterator();long time21 = Calendar.getInstance().getTimeInMillis();while(it1.hasNext()){Object key = it1.next();Object value = map.get(key);System.out.println(key+":"+value);}long time22 = Calendar.getInstance().getTimeInMillis();System.out.println("第一种方法用时:"+(time12-time11));System.out.println("第二种方法用时:"+(time22-time21));
上面代码块有两种遍历的方法,

1.利用entrySet()函数返回返回此映射所包含的映射关系的 Set 视图。然后用Map.Entry的getKey()和getValue()方法就将集合中的键值对取出来了

2.利用keySet()函数返回此映射中所包含的键的 Set 视图。然后根据迭代器取出的key值,利用get()方法将值取出。

在效率方面经过多次测试,第二种要比第一种效率高。我在其他文章上看到说是第一种效率更高,其实不然,测试截图如下:


1 0
原创粉丝点击