原文: https://beginnersbook.com/2013/12/how-to-loop-hashmap-in-java/

在本教程中,我们将学习如何使用以下方法循环HashMap

  1. for循环
  2. while循环 + 迭代器

示例:

在下面的示例中,我们使用两种方法(for循环和while循环)迭代HashMap。在while循环中,我们使用了迭代器。

  1. package beginnersbook.com;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import java.util.Iterator;
  5. public class Details
  6. {
  7. public static void main(String [] args)
  8. {
  9. HashMap<Integer, String> hmap = new HashMap<Integer, String>();
  10. //Adding elements to HashMap
  11. hmap.put(11, "AB");
  12. hmap.put(2, "CD");
  13. hmap.put(33, "EF");
  14. hmap.put(9, "GH");
  15. hmap.put(3, "IJ");
  16. //FOR LOOP
  17. System.out.println("For Loop:");
  18. for (Map.Entry me : hmap.entrySet()) {
  19. System.out.println("Key: "+me.getKey() + " & Value: " + me.getValue());
  20. }
  21. //WHILE LOOP & ITERATOR
  22. System.out.println("While Loop:");
  23. Iterator iterator = hmap.entrySet().iterator();
  24. while (iterator.hasNext()) {
  25. Map.Entry me2 = (Map.Entry) iterator.next();
  26. System.out.println("Key: "+me2.getKey() + " & Value: " + me2.getValue());
  27. }
  28. }
  29. }

输出:

  1. For Loop:
  2. Key: 2 & Value: CD
  3. Key: 3 & Value: IJ
  4. Key: 33 & Value: EF
  5. Key: 9 & Value: GH
  6. Key: 11 & Value: AB
  7. While Loop:
  8. Key: 2 & Value: CD
  9. Key: 3 & Value: IJ
  10. Key: 33 & Value: EF
  11. Key: 9 & Value: GH
  12. Key: 11 & Value: AB

参考: