Iterating over a HashMap is an essential skill for Java developers, as it enables data manipulation, retrieval, and processing. In this article, we will explore iterate hashmap java over .
## 1. Using for-each Loop with EntrySet
The `entrySet()` method returns a set of key-value pairs, which can be iterated using a for-each loop. This is one of the most efficient ways to traverse a HashMap.
import java.util.HashMap;
import java.util.Map;
public class HashMapIteration {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "Apple");
map.put(2, "Banana");
map.put(3, "Cherry");
```
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
```
}
## 2. Using keySet() for Iterating Keys
If you only need to iterate over keys, you can use the `keySet()` method.
for (Integer key : map.keySet()) {
System.out.println("Key: " + key);
}
## 3. Using values() for Iterating Values
Similarly, if only values are required, `values()` can be used.
for (String value : map.values()) {
System.out.println("Value: " + value);
}
## Conclusion
There are multiple ways to iterate over a HashMap in Java, each with its own use case. The `for-each` loop with `entrySet()` is commonly used for its simplicity, while `forEach()` and Streams provide modern and efficient alternatives. Choosing the right method depends on the specific requirements of your program.