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 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".
Answer
There are various ways to achieve this. Here are three.
Map map = new HashMap();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
System.out.println("using entrySet and toString");
for (Entry entry : map.entrySet()) {
System.out.println(entry);
}
System.out.println();
System.out.println("using entrySet and manual string creation");
for (Entry 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
No comments:
Post a Comment