在这个例子中,我们将看到如何使用Iterator迭代HashMap并显示键和值对。我们在下面的例子中遵循的步骤如下:
1)创建HashMap并用键值对填充它。
2)通过调用entrySet()方法获取键值对集合。
3)获取入口集的迭代器。
4)使用Map.Entry接口的getKey()和getValue()方法显示键值对。
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()); } }}
输出:
HashMap Key-Value Pairs : Key is: 33 & value is: Value3Key is: 55 & value is: Value5Key is: 22 & value is: Value2Key is: 11 & value is: Value1Key is: 44 & value is: Value4
