What is the method for iterating and outputting a HashMap in Java?
In Java, there are two methods available to iterate and output a HashMap:
- Utilizing iterators.
HashMap<String, Integer> map = new HashMap<>();
// 添加元素到map...
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("Key: " + key + ", Value: " + value);
}
- Use a for-each loop:
HashMap<String, Integer> map = new HashMap<>();
// 添加元素到map...
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("Key: " + key + ", Value: " + value);
}
Whether using an iterator or a for-each loop, you can retrieve key-value pairs from a HashMap by using Map.Entry. You can then use entry.getKey() to get the key and entry.getValue() to get the corresponding value. Formatting can be adjusted as needed when outputting.