关于Java:Map,如何同时打印”key string”和”value string”

Map<String, String>, how to print both the “key string” and “value string” together

本问题已经有最佳答案,请猛点这里访问。

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

我想出了下面的代码。但是,我想同时打印出"key string"和"value string"。

1
2
3
4
5
6
7
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    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();

产量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

在循环内部,您有一个键,可以使用它从Map中检索值:

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


1
2
3
4
5
6
7
final Map<String, String> mss1 = new ProcessBuilder().environment();
mss1.entrySet()
        .stream()
        //depending on how you want to join K and V use different delimiter
        .map(entry ->
        String.join(":", entry.getKey(),entry.getValue()))
        .forEach(System.out::println);