How to for each the hashmap?

To iterate over the key-value pairs in a HashMap in Java, you can use the forEach() method and provide a lambda expression as an argument. Here's an example:

HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("cherry", 3);

map.forEach((key, value) -> System.out.println(key + ": " + value));

This will print the following output:

apple: 1
banana: 2
cherry: 3

Alternatively, you can use the entrySet() method to get a set of the map's key-value pairs and iterate over that set using a for loop or an iterator:

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

This will produce the same output as the forEach() method.