Map to String in Java
Asked Answered
B

2

106

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)?

Bohemianism answered 13/5, 2010 at 15:55 Comment(0)
R
168

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).

Resultant answered 13/5, 2010 at 15:56 Comment(9)
Pressing F3 on the Map toString() method is misleading! Takes you straight to the Object.toString() - should think before engaging F3Butene
@Adam, that's because you call toString() on the interface, where this method, of course, is not defined. Your IDE doesn't know about actual run-time implementation. You should not blame her.Persis
@VictorDombrovsky Any half-decent IDE (e.g. IntelliJ, Eclipse, etc.) should be able to track down the actual implementation of a method defined in an interface.Lapsus
@Lapsus toString() isn't declared in Map and if it were: Map has 21 implementing classes. Which of them should be preferred over the others when the implementation actually used is only known at runtime?Lucknow
But the key values are not double-quoted though, hence not a valid JSON if someone tries to use it as JSONVc
@PSatishPatro: just use a JSON encoder. A lot of them also support Map.Resultant
Yeah, I used Gson library.Vc
@GeroldBroser At least in my IDE (IntelliJ IDEA), it will give me a list of potential possible implementations that are in the classpath of the project I am working on. It's up to the judgement of the developer to figure out which one will be selected, since the selection of the implementing class will usually be deterministic, it should not be a total mystery.Lapsus
need to highlight that String.valueOf(map) is a better choice to handle null mapsKlong
L
12

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

Joiner.on(",").withKeyValueSeparator("=").join(map);
Lavern answered 13/5, 2010 at 19:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.