I am wondering is it possible to print the keys and associated values of a map on separate lines. I am new to Java and to maps. When I try printing using the normal println
as on the last line it prints out the keys and value's inside a curly brace and all on 1 line. I know this is probably a silly question but I have been struggling with it for a while now and have not found a solution online or in any of my lecture notes. This is just a class I set up to try get it working before I try implement it on a bigger scale. Sorry in advance if my code or anything else does not appear in a conventional way, this is my first time to post.
import java.util.TreeMap;
public class tester {
public static void main(String[] args){
TreeMap<String, String> dir = new TreeMap<String, String>();
String key = "b";
String value = "2";
String key1 = "a";
String value2 = "1";
dir.put(key, value);
dir.put(key1, value2);
System.out.println(dir);
}
}
Yep, you have to loop through the map and print the keys and values on separate lines.
TreeMap<String, String> dir = new TreeMap<String, String>();
for(Entry<String, String> en: dir.entrySet()) {
System.out.println(en.getKey());
System.out.println(en.getValue());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With