本文介绍了映射< String,String> ;,如何同时打印"key string"和"key string".和“值字符串"一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Java的新手,正在尝试学习Maps的概念.
I'm new to Java and is trying to learn the concept of 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".
推荐答案
有多种方法可以实现此目的.这是三个.
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();
输出
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
这篇关于映射< String,String> ;,如何同时打印"key string"和"key string".和“值字符串"一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!