1.通过构造HashMap的entrySet来迭代
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"); 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); } } }
2.先取得HashMap的keySet,再用get(key)访问
if(hashMap!=null || !hashMap.isEmpty()){ 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更快一点,写段代码测试了一下,确实如此。
public class TestUnit { public static void main(String[] args) { HashMap<Integer, String> hashMap = new HashMap(); for (int i = 0; i < 1000; i++) { hashMap.put(i, "Hello World!"); } keySetTest(hashMap); entrySetTest(hashMap); } static void keySetTest(Map map) { long startTime = Calendar.getInstance().getTimeInMillis(); Iterator iter = map.keySet().iterator(); while (iter.hasNext()) { System.out.print(map.get(iter.next())); } long endTime = Calendar.getInstance().getTimeInMillis(); System.out.println("\nkeySetTest : " + (endTime - startTime)); // 60 ms } static void entrySetTest(Map map) { long startTime = Calendar.getInstance().getTimeInMillis(); Iterator iter = map.entrySet().iterator(); Map.Entry mapEntry; while (iter.hasNext()) { mapEntry = (Map.Entry) iter.next(); System.out.print(mapEntry.getValue()); } long endTime = Calendar.getInstance().getTimeInMillis(); System.out.println("\nentrySetTest : " + (endTime - startTime)); // 13 ms } }
原因分析:
- 使用keySet方法访问时,构建的Set只由key组成,访问每一个value时要重新计算Hash值然后根据Hash值到Map中查找value;
- 使用entrySet方法访问时,构建的Set直接由<key,value>组成,访问每一个value时直接取就行,无需计算Hash值。
时间: 2024-10-09 13:45:07