Can I print keys and associated map values ​​on separate lines in Java?

I am wondering if it is possible to print the keys and associated map values ​​in separate lines. I am new to Java and maps. When I try to print using the regular println command, as on the last line, it prints the keys and value inside the curly brace and all on the same line. I know that this is probably a stupid question, but I struggled with it for a while and did not find a solution on the Internet or in any of my lectures. This is just a class that I created to try to get it to work before trying to implement it on a larger scale. Sorry in advance if my code or something else does not appear in the usual way, this is my first 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); } } 
+4
source share
3 answers

Yes, you need to go around 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()); } 
+2
source

Yes...

 for (String key : dir.keySet()) { System.out.println(key + " = " + dir.get(key)); } 

Check out the Map API for more information.

UPDATED with a return back from Mik378

As suggested by Mik378, to get better performance, you'd better use Map.entrySet ( Accessing map values ​​using keySet iterator )

 for(Map.Entry<String, String> entry : dir.entrySet()) { System.out.println(entry.getKey() + " = " + entry.getValue()); } 
+1
source

Replace the last line with:

 for(Map.Entry<String, String> entry : dir.entrySet()) { System.out.println(entry); } 

It will display:

 a=1 b=2 

Indeed, the Entry toString() method is already equal:

 public String toString() { return key + "=" + value; } 
+1
source

Source: https://habr.com/ru/post/1443341/


All Articles