Pretty-print a Map in Java
Make your Java Map
picture-perfect by utilizing Java 8 streams for a neat, precise string output:
Behold! A tidy {key1=value1, key2=value2, ...}
is outputted.
Array of options for toString()
Unbeknownst to many, the Map
's base toString()
is not the end-all-be-all of map-to-string conversions. For bespoke formatting requirement or unique key-value separators, one can leverage libraries like Guava or the power of Java 8 to reach the apex of pretty-print customization.
Arrays.toString(): Where simplicity reigns
To dodge the streams, consider the below approach:
This single-line code yields a straightforward representation of your entire Map
as an array of strings—genuinely pretty-printed.
Custom Formatting with PrettyPrintingMap
What if your requirements dictate your Map
entries to be printed as key="value"
? Fear not, let's create a custom PrettyPrintingMap
:
Here you have a neatly packaged logic for your frequent pretty-printing tasks.
Guava: A utility celebrity
If you're the type who trusts external libraries for handling formatting, take a glance at Guava's MapJoiner
:
This is for those who favor elegance and simplicity in their code.
The JSON way for complex structures
Suppose your Map
mirrors a JSON-like nested data structure. In that case, voila! JSON's formatting tools come to your rescue. With JSONObject
, you can achieve pretty-print magic:
The 2
here isn't a lucky number. It specifies the indentation level for nested structures.
Practical examples for better understanding
Utility over repetition
Imagine having to pretty-print maps frequently across your codebase. You don't want to repeatedly write the same code. This use-case is where the utility of PrettyPrintingMap
truly shines.
Logging with a touch of elegance
There might be scenarios where the toString()
output is simply inadequate for logging/debugging. Here, Guava MapJoiner
can provide better visibility into your Map
behavior.
JSON formatting for the win
In situations where a Map
is portraying complex data, JSON formatting works like magic. The indentation using JSONObject
's toString
makes even deeply nested objects a breeze to comprehend.
Code refinement snippets & recommendations
Streamline your streams
When dealing with streams, amalgamate methods and operations to cut down on the number of data passes. Here's a compact formatting routine that also handles nulls effectively:
Maven and Guava – BFFs
Using Guava? Integrate it with Maven swiftly by adding the dependency in your pom.xml
:
MultiData type Map? No problem.
A Map
may contain various types of values. While formatting, use Object.toString()
judiciously to prevent ClassCastException or other formatting bloopers.
Harness the power of PrettyPrintingMap
Once you've decided on PrettyPrintingMap
, consider incorporating it as a reusable component. It's an efficient tool for generating uniform map representations across applications.
Was this article helpful?