Java

java怎么打印map中的数据

小亿
306
2024-05-16 17:47:16
栏目: 编程语言

在Java中,可以通过遍历Map中的键值对来打印Map中的数据。以下是一个示例代码:

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

public class Main {
    public static void main(String[] args) {
        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()) {
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }
    }
}

在上面的代码中,我们创建了一个HashMap对象,然后向其中添加了一些键值对。接着使用entrySet()方法获取Map中的键值对集合,然后通过遍历这个集合来打印每个键值对的键和值。

0
看了该问题的人还看了