ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# 如何在 java 中循环`HashMap` > 原文: [https://beginnersbook.com/2013/12/how-to-loop-hashmap-in-java/](https://beginnersbook.com/2013/12/how-to-loop-hashmap-in-java/) 在本教程中,我们将学习如何使用以下方法循环`HashMap`: 1. `for`循环 2. `while`循环 + 迭代器 **示例:** 在下面的示例中,我们使用两种方法(`for`循环和`while`循环)迭代`HashMap`。在`while`循环中,我们使用了迭代器。 ```java package beginnersbook.com; import java.util.HashMap; import java.util.Map; import java.util.Iterator; public class Details { public static void main(String [] args) { HashMap<Integer, String> hmap = new HashMap<Integer, String>(); //Adding elements to HashMap hmap.put(11, "AB"); hmap.put(2, "CD"); hmap.put(33, "EF"); hmap.put(9, "GH"); hmap.put(3, "IJ"); //FOR LOOP System.out.println("For Loop:"); for (Map.Entry me : hmap.entrySet()) { System.out.println("Key: "+me.getKey() + " & Value: " + me.getValue()); } //WHILE LOOP & ITERATOR System.out.println("While Loop:"); Iterator iterator = hmap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry me2 = (Map.Entry) iterator.next(); System.out.println("Key: "+me2.getKey() + " & Value: " + me2.getValue()); } } } ``` 输出: ```java For Loop: Key: 2 & Value: CD Key: 3 & Value: IJ Key: 33 & Value: EF Key: 9 & Value: GH Key: 11 & Value: AB While Loop: Key: 2 & Value: CD Key: 3 & Value: IJ Key: 33 & Value: EF Key: 9 & Value: GH Key: 11 & Value: AB ``` #### 参考: * [`Iterator` javadoc](https://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html) * [`HashMap` 文档](https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html)