歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java中遍歷HashMap的方法

Java中遍歷HashMap的方法

日期:2017/3/1 10:07:23   编辑:Linux編程

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. }

第一種效率要高於第二種,應盡量使用第一種進行遍歷。

Copyright © Linux教程網 All Rights Reserved