💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# Java - `HashMap Iterator` > 原文: [https://beginnersbook.com/2014/07/java-hashmap-iterator-example/](https://beginnersbook.com/2014/07/java-hashmap-iterator-example/) #### 示例 在上一个教程中,我们看到了[不同的 2 种迭代`HashMap`](https://beginnersbook.com/2013/12/how-to-loop-hashmap-in-java/)的方法。在这个例子中,我们将看到如何使用[`Iterator`](https://beginnersbook.com/2014/06/java-iterator-with-examples/)迭代[`HashMap`](https://beginnersbook.com/2013/12/hashmap-in-java-with-example/)并显示键和值对。我们在下面的例子中遵循的步骤如下: 1)创建[`HashMap`](https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html) 并用键值对填充它。 2)通过调用`entrySet()`方法获取键值对集合。 3)获取入口集的迭代器。 4)使用[`Map.Entry`接口](https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html)的`getKey()`和`getValue()`方法显示键值对。 ```java import java.util.HashMap; import java.util.Set; import java.util.Iterator; import java.util.Map; public class HashMapIteratorExample { public static void main(String[] args) { // Creating a HashMap of int keys and String values HashMap<Integer, String> hashmap = new HashMap<Integer, String>(); // Adding Key and Value pairs to HashMap hashmap.put(11,"Value1"); hashmap.put(22,"Value2"); hashmap.put(33,"Value3"); hashmap.put(44,"Value4"); hashmap.put(55,"Value5"); // Getting a Set of Key-value pairs Set entrySet = hashmap.entrySet(); // Obtaining an iterator for the entry set Iterator it = entrySet.iterator(); // Iterate through HashMap entries(Key-Value pairs) System.out.println("HashMap Key-Value Pairs : "); while(it.hasNext()){ Map.Entry me = (Map.Entry)it.next(); System.out.println("Key is: "+me.getKey() + " & " + " value is: "+me.getValue()); } } } ``` 输出: ```java HashMap Key-Value Pairs : Key is: 33 & value is: Value3 Key is: 55 & value is: Value5 Key is: 22 & value is: Value2 Key is: 11 & value is: Value1 Key is: 44 & value is: Value4 ```