1.使用for_each循环迭代
View Code
public class TestUnit { public static void main(String[] args) { HashMap hashMap=new HashMap<Integer,String>(); hashMap.put(1,"aaa"); hashMap.put(2,"bbb"); hashMap.put(3,"ccc"); for(Object m:hashMap.entrySet()) { Map.Entry mapEntry=(Map.Entry)m; Object key=mapEntry.getKey(); Object value=mapEntry.getValue(); System.out.println("key="+key+",value="+value); } } }
2.通过构造HashMap的entrySet来迭代
Iterator iter=hashMap.entrySet().iterator(); while(iter.hasNext()){ Map.Entry mapEntry=(Map.Entry) iter.next(); Object key=mapEntry.getKey(); Object value=mapEntry.getValue(); System.out.println("key="+key+",value="+value); }
3.先取得HashMap的keySet,再用get(key)访问
Set set=hashMap.keySet(); Iterator iter=set.iterator(); while(iter.hasNext()){ Object key=iter.next(); Object value=hashMap.get(key); System.out.println("key="+key+",value="+value); }
Test
据说是用entrySet更快一点,写段代码测试了一下,确实如此。(纠正:后来发现测试存在问题,谁先执行谁的耗时要多一点,估计是和第一个需要开辟输出缓冲区有关)
import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class TestUnit { public static void main(String[] args) { HashMap<Integer, String> hashMap = new HashMap(); for (int i = 0; i < 10000; i++) { hashMap.put(i, "Hello World!"); } forEachTest(hashMap); entrySetTest(hashMap); keySetTest(hashMap); } static long forEachTest(Map map){ long startTime = System.currentTimeMillis(); for(Object m:map.entrySet()) { Map.Entry mapEntry=(Map.Entry)m; System.out.print(mapEntry.getValue()); } long endTime = System.currentTimeMillis(); System.out.println("\nforEachTest : " + (endTime - startTime)); return endTime - startTime; } static long keySetTest(Map map) { long startTime = System.currentTimeMillis(); Iterator iter = map.keySet().iterator(); while (iter.hasNext()) { System.out.print(map.get(iter.next())); } long endTime = System.currentTimeMillis(); System.out.println("\nkeySetTest : " + (endTime - startTime)); return endTime - startTime; } static long entrySetTest(Map map) { long startTime = System.currentTimeMillis(); Iterator iter = map.entrySet().iterator(); Map.Entry mapEntry; while (iter.hasNext()) { mapEntry = (Map.Entry) iter.next(); System.out.print(mapEntry.getValue()); } long endTime = System.currentTimeMillis(); System.out.println("\nentrySetTest : " + (endTime - startTime)); return endTime - startTime; } }
原因分析:
- 使用keySet方法访问时,构建的Set只由key组成,访问每一个value时要重新计算Hash值然后根据Hash值到Map中查找value;
- 使用entrySet方法访问时,构建的Set直接由<key,value>组成,访问每一个value时直接取就行,无需计算Hash值。