java - Map<String, String>,如何同时打印 "key string"和 "value string"

标签 java dictionary key

我是 Java 新手,正在尝试学习 map 的概念。

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

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

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

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

最佳答案

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

    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

关于java - Map<String, String>,如何同时打印 "key string"和 "value string",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35642493/

相关文章:

Python--查找嵌套字典中特定值的父键

java - 错误 : Could not find or load main class net. sourceforge.cobertura.merge.Main

java - 使用扫描仪输入和正/负数的“while”无限循环

java - Feign请求拦截器动态值

java - 如何在java中使用ReadWriteLock实现A Cache?

swift - 在字典数组中找到最大值

c# - 从数组列表中获取字典

java - 我无法使用sharedPreferences android studio 获取第一个字符串

regex - Google App Engine key 中允许使用哪些字符?

php-redis (new Redis()) getKeys() 方法使用 "KEYS *"或 "SCAN"进行迭代?