[Java Tips] Printing java.util.Map contents

Printing java.util.Map contents is quite a common use case. Most of the time end implementing the same logic of using iterator and writing to Console. Let's explore a simpler way and taste goodness of Google Guava.

Code can be found at MapPrinter.java

public static void printMapOnConcole(Map map) {
    Preconditions.checkNotNull(map);
    Joiner.MapJoiner mapJoiner = Joiner.on("\n").withKeyValueSeparator("=");
    System.out.println(mapJoiner.join(map));
}

Here we use the MapJoiner provided by to concatenate the contents of our java.util.Map instance.

Usage example

Map<String, String> maps = new HashMap<String, String>();
maps.put("key1", "value1");
maps.put("key2", "value2");
maps.put("key3", "value3");
printMapOnConcole(maps);

Output is something like

key1=value1
key2=value2
key3=value3

An over-loaded utility method is present on github, which accepts record separator and key-value separator as well.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.