Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map to String in Java

Tags:

java

tostring

map

When I do System.out.println(map) in Java, I get a nice output in stdout. How can I obtain this same string representation of a Map in a variable without meddling with standard output? Something like String mapAsString = Collections.toString(map)?

like image 811
Dan Avatar asked May 13 '10 15:05

Dan


People also ask

How do I convert a map to a String in Java?

Use Object#toString() . String string = map. toString();

How do you set a String on a map?

Now need is to convert the String to a Map object so that each student roll number becomes the key of the HashMap, and the name becomes the value of the HashMap object. In order to convert strings to HashMap, the process is divided into two parts: The input string is converted to an array of strings as output.

Can we map a String?

8 Answers. Show activity on this post. Then you can create a Map<String,ComputeString> object like you want in the first place. Using a map will be much faster than reflection and will also give more type-safety, so I would advise the above.


2 Answers

Use Object#toString().

String string = map.toString(); 

That's after all also what System.out.println(object) does under the hoods. The format for maps is described in AbstractMap#toString().

Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).

like image 200
BalusC Avatar answered Sep 17 '22 18:09

BalusC


You can also use google-collections (guava) Joiner class if you want to customize the print format

Joiner.on(",").withKeyValueSeparator("=").join(map); 
like image 30
Aravind Yarram Avatar answered Sep 19 '22 18:09

Aravind Yarram