How to use the foreach method in a hashmap?

The forEach method of HashMap can be implemented by iterating over the entrySet of HashMap. The entrySet method returns a Set collection containing key-value pairs, which can be iterated to access each key-value pair and perform the corresponding operation on them.

Here is an example code using the foreach method with HashMap:

import java.util.HashMap;
import java.util.Map;

public class HashMapExample {
    public static void main(String[] args) {
        // 创建一个HashMap
        Map<String, Integer> map = new HashMap<>();
        map.put("A", 1);
        map.put("B", 2);
        map.put("C", 3);

        // 使用foreach方法遍历HashMap
        map.forEach((key, value) -> System.out.println(key + " : " + value));
    }
}

The above code creates a HashMap, adds three key-value pairs using the put method, then iterates through the HashMap using the forEach method, executing a Lambda expression for each key-value pair to print the key and value.

Running the above code will result in:

A : 1
B : 2
C : 3

This makes it possible to use the forEach method of HashMap.

bannerAds