Java中遍历HashMap的方法


Java中,通常有两种遍历HashMap的方法,如下:

  1. import java.util.*;
  2. publicclass MapTest {
  3. static HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
  4. publicstaticvoid main(String [] args) {
  5. hashMap.put("one", 1);
  6. hashMap.put("two", 2);
  7. hashMap.put("three", 3);
  8. hashMap.put("four", 4);
  9. hashMap.put("five", 5);
  10. Iterator iter = hashMap.entrySet().iterator();
  11. // the first method to travel the map
  12. while (iter.hasNext()) {
  13. Map.Entry<String, Integer> entry = (Map.Entry<String, Integer>) iter.next();
  14. String key = entry.getKey();
  15. Integer value = entry.getValue();
  16. System.out.println(key + " " + value);
  17. }
  18. iter = hashMap.keySet().iterator();
  19. // the second method to travel the map
  20. while (iter.hasNext()) {
  21. String key = (String) iter.next();
  22. Integer value = hashMap.get(key);
  23. System.out.println(key + " " + value);
  24. }
  25. } // close main()
  26. }

第一种效率要高于第二种,应尽量使用第一种进行遍历。

相关内容