Explain Codes LogoExplain Codes Logo

Pretty-print a Map in Java

java
pretty-printing
map-formatting
java-8
Nikita BarsukovbyNikita Barsukov·Nov 23, 2024
TLDR

Make your Java Map picture-perfect by utilizing Java 8 streams for a neat, precise string output:

String prettyPrintedMap = map.entrySet() .stream() .map(e -> e.getKey() + "=" + e.getValue()) .collect(Collectors.joining(", ", "{", "}"));

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:

String mapAsString = Arrays.toString(map.entrySet().toArray());

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:

public class PrettyPrintingMap<K, V> { private Map<K, V> map; public PrettyPrintingMap(Map<K, V> map){ this.map = map; } @Override public String toString(){ // Keys and values stick together like bread and butter. return map.entrySet() .stream() .map(entry -> "\"" + entry.getKey() + "\"=\"" + entry.getValue() + "\"") .collect(Collectors.joining(", ", "{", "}")); } }

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:

MapJoiner mapJoiner = Joiner.on(", ").withKeyValueSeparator("="); // Guava: Extracting beauty from confusion since '07! System.out.println(mapJoiner.join(map));

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:

JSONObject json = new JSONObject(map); System.out.println(json.toString(2));

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:

String pretty = map.entrySet().stream() .map(e -> String.format("%s=%s", e.getKey(), e.getValue() == null ? "null" : e.getValue())) // No more pesky 'NullPointerException.' .collect(Collectors.joining(", ", "{", "}"));

Maven and Guava – BFFs

Using Guava? Integrate it with Maven swiftly by adding the dependency in your pom.xml:

<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>YOUR_VERSION</version> // Be sure to replace 'YOUR_VERSION' with the actual version number. No, 'YOUR_VERSION' is not a new software version. 😆 </dependency>

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.