Java Map<String, String>,如何同时打印“键串”和“值串”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35642493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Map<String, String>, how to print both the "key string" and "value string" together
提问by Thor
I'm new to Java and is trying to learn the concept of Maps.
我是 Java 新手,正在尝试学习 Maps 的概念。
I have came up with the code below. However, I want to print out the "key String" and "value String" at the same time.
我想出了下面的代码。但是,我想同时打印出“键字符串”和“值字符串”。
ProcessBuilder pb1 = new ProcessBuilder();
Map<String, String> mss1 = pb1.environment();
System.out.println(mss1.size());
for (String key: mss1.keySet()){
System.out.println(key);
}
I could only find method that print only the "key String".
我只能找到只打印“密钥字符串”的方法。
采纳答案by Stefan Dollase
There are various ways to achieve this. Here are three.
有多种方法可以实现这一点。这里是三个。
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();
Output
输出
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
回答by blacktide
Inside of your loop, you have the key, which you can use to retrieve the value from the Map
:
在您的循环内部,您有密钥,您可以使用该密钥从 中检索值Map
:
for (String key: mss1.keySet()) {
System.out.println(key + ": " + mss1.get(key));
}
回答by dmitryvinn
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);