hashmap 遍历

引用:http://apps.hi.baidu.com/share/detail/50038621

一。Java中遍历HashMap的两种方式
第一种:
  HashMap<String,String> keySetMap = new HashMap<String,String>();
  Iterator<String> keySetIterator = keySetMap.keySet().iterator();
   while (keySetIterator.hasNext()) {
      System.out.println(keySetMap.get(keySetIterator.next()));
   }

第二种:
  HashMap<String,String> entrySetMap=new HashMap<String,String>();
  Iterator<Entry<String,String>> entrySetIterator=entrySetMap.entrySet().iterator();
   while(entrySetIterator.hasNext()){
      Entry<String,String> entry=entrySetIterator.next();
      System.out.println(entry.getValue());
   }
二。哪种方式更好?
HashMap的遍历有两种常用的方法,那就是使用keyset和entryset来进行遍历,但两者的遍历速度是有差别的,到底哪一种方式更好呢?测试一下就知道了。下面请看实例:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

public class HashMapTest {
    public static void main(String[] args) {
        HashMap<String,String> keySetMap = new HashMap<String,String>();
        HashMap<String,String> entrySetMap=new HashMap<String,String>();
        
        for (int i= 0;i<1000;i++) {
            keySetMap.put(""+i, "keySet");
        }
        for(int i=0;i<1000;i++){
            entrySetMap.put(""+i,"entrySet");
        }
        
        long startTimeOne = System.currentTimeMillis();
        Iterator<String> keySetIterator = keySetMap.keySet().iterator();
        while (keySetIterator.hasNext()) {
            System.out.println(keySetMap.get(keySetIterator.next()));
        }
        System.out.println("keyset遍历时间:"+(System.currentTimeMillis()-startTimeOne));
        
        long startTimeTwo=System.currentTimeMillis();
        Iterator<Entry<String,String>> entrySetIterator=entrySetMap.entrySet().iterator();
        while(entrySetIterator.hasNext()){
            Entry<String,String> entry=entrySetIterator.next();
            System.out.println(entry.getValue());
        }
        System.out.println("entryset遍历时间:"+(System.currentTimeMillis()-startTimeTwo));
    }
}
通过多次运行测试发现,entryset遍历时间比keyset遍历时间短许多,entryset方式的性能通常要比keyset方式高一倍。
三。原因何在?
  通过查看源代码发现,调用keySetMap.keySet()这个方法会生成keyIterator迭代器,其next()方法只返回其key值,然后再通过key值在keySetMap中获得其value值,代码如:keySetMap.get(keySetIterator.next())
  而调用entrySetMap.entrySet()方法会生成EntryIterator迭代器,其next()方法返回一个Entry对象的一个实例,其中包含key值和value值。
  如果遍历HashMap时只取其key值,那么两种方式的遍历在性能上应该是相同的。但同时取key值和value值时,keyset方式比entryset方式多遍历了一次table,此时keyset方式性能差些。

原文地址:https://www.cnblogs.com/sode/p/2375020.html