Map to String in Java

JavaMapTostring

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Joiner.on(",").withKeyValueSeparator("=").join(map);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDanView Question on Stackoverflow
Solution 1 - JavaBalusCView Answer on Stackoverflow
Solution 2 - JavaAravind YarramView Answer on Stackoverflow