Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to print the keys and associated values of a map on separate lines in Java?

Tags:

java

maps

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);
    }
}
like image 738
Niall Byrne Avatar asked Oct 06 '22 03:10

Niall Byrne


1 Answers

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());
}
like image 159
PermGenError Avatar answered Oct 10 '22 02:10

PermGenError