Map<String, String>, 如何将“键字符串”和“值字符串”一起打印

2022-09-03 03:43:40

我是Java的新手,正在努力学习地图的概念。

我想出了下面的代码。但是,我想同时打印出“键字符串”和“值字符串”。

ProcessBuilder pb1 = new ProcessBuilder();
Map<String, String> mss1 = pb1.environment();
System.out.println(mss1.size());

for (String key: mss1.keySet()){
    System.out.println(key);
}

我只能找到只打印“键字符串”的方法。


答案 1

有多种方法可以实现这一目标。这里有三个。

    Map<String, String> map = new HashMap<String, String>();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("key3", "value3");

    System.out.println("using entrySet and toString");
    for (Entry<String, String> entry : map.entrySet()) {
        System.out.println(entry);
    }
    System.out.println();

    System.out.println("using entrySet and manual string creation");
    for (Entry<String, String> entry : map.entrySet()) {
        System.out.println(entry.getKey() + "=" + entry.getValue());
    }
    System.out.println();

    System.out.println("using keySet");
    for (String key : map.keySet()) {
        System.out.println(key + "=" + map.get(key));
    }
    System.out.println();

输出

using entrySet and toString
key1=value1
key2=value2
key3=value3

using entrySet and manual string creation
key1=value1
key2=value2
key3=value3

using keySet
key1=value1
key2=value2
key3=value3

答案 2

在循环内部,您有键,可用于从 中检索值:Map

for (String key: mss1.keySet()) {
    System.out.println(key + ": " + mss1.get(key));
}