In Java, you can iterate over a Map using several methods to access its keys, values, or key-value pairs. The most common ways include:
1. Using for-each loop and entrySet():
This is the most common method to iterate over both keys and values.
java
Map<String, Integer> map = new HashMap<>();
map.put(“A”, 1);
map.put(“B”, 2);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(“Key: ” + entry.getKey() + “, Value: ” + entry.getValue());
}
2. Using for-each loop and keySet():
Iterate over keys and then fetch values.
java
for (String key : map.keySet()) {
System.out.println(“Key: ” + key + “, Value: ” + map.get(key));
}
3. Using for-each loop and values():
Iterate over values only.
java
for (Integer value : map.values()) {
System.out.println(“Value: ” + value);
}
4. Using Iterator:
Iterate using an Iterator for entrySet().
java
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
System.out.println(“Key: ” + entry.getKey() + “, Value: ” + entry.getValue());
}
These methods allow efficient access to the elements of a Map in Java.