In Java, a HashMap is a collection that stores key-value pairs. The keySet() method of the HashMap class returns a set of all keys contained in the map.
Here’s an example of using the keySet() method to iterate over all keys in a HashMap:
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
// Create a new HashMap
Map<String, Integer> map = new HashMap<>();
// Add some key-value mappings to the map
map.put("John", 28);
map.put("Alice", 35);
map.put("Bob", 42);
// Get a set of all keys in the map
for (String key : map.keySet()) {
Integer value = map.get(key);
System.out.println(key + " = " + value);
}
}
}
In this example, we create a new HashMap called map and add three key-value mappings to it. We then use the keySet() method to get a set of all keys in the map, and iterate over each key in the set using a for-each loop.
Inside the loop, we use the get() method of the HashMap class to retrieve the value associated with each key. We then print out the key and value using System.out.println(). The output of this program would be:
John = 28
Alice = 35
Bob = 42
This demonstrates how to use the keySet() method to iterate over all keys in a HashMap and access their associated values.
