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)
?
Asked
Active
Viewed 2.3e+01k times
106
2 Answers
164
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 byString.valueOf(Object)
.

BalusC
- 1,082,665
- 372
- 3,610
- 3,555
-
3Pressing F3 on the Map toString() method is misleading! Takes you straight to the Object.toString() - should think before engaging F3 – Adam May 21 '15 at 14:36
-
2@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. – Victor Dombrovsky May 11 '16 at 16:30
-
@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. – wheeler Mar 14 '17 at 14:03
-
@wheeler `toString()` isn't declared in [`Map`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Map.html#method.summary) 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? – Gerold Broser Jul 17 '20 at 20:19
-
1But the key values are not double-quoted though, hence not a valid JSON if someone tries to use it as JSON – Satish Patro Jul 27 '20 at 15:13
-
@PSatishPatro: just use a JSON encoder. A lot of them also support `Map`. – BalusC Jul 27 '20 at 15:27
-
Yeah, I used Gson library. – Satish Patro Jul 28 '20 at 05:07
-
@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. – wheeler Aug 05 '20 at 02:57
-
need to highlight that String.valueOf(map) is a better choice to handle null maps – kisna Apr 30 '21 at 04:59
12
You can also use google-collections (guava) Joiner class if you want to customize the print format
Joiner.on(",").withKeyValueSeparator("=").join(map);

msangel
- 9,895
- 3
- 50
- 69

Aravind Yarram
- 78,777
- 46
- 231
- 327