How to iterate through a Map using Java?

One common way to iterate through a Map in Java is to use the entrySet() method, which converts the Map into a Set and returns a Set collection containing all key-value pairs in the Map. You can then use an enhanced for loop to iterate through the Set collection, and access the keys and values using the getKey() and getValue() methods for each key-value pair.

Here is an example code:

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

public class MapTraversalExample {
    public static void main(String[] args) {
        // 创建一个Map对象并添加一些键值对
        Map<String, Integer> map = new HashMap<>();
        map.put("A", 1);
        map.put("B", 2);
        map.put("C", 3);

        // 使用entrySet()方法遍历Map
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            String key = entry.getKey();
            Integer value = entry.getValue();
            System.out.println("Key: " + key + ", Value: " + value);
        }
    }
}

Running the code above will produce:

Key: A, Value: 1
Key: B, Value: 2
Key: C, Value: 3

By iterating through the Set collection returned by entrySet(), you can access each key-value pair in the Map, and then individually access the keys and values for respective operations.

bannerAds