In this article, we will see how to pretty print a map in Java and make it easier to visualize the key-value pairs.

Let us first create an example map to show how to do a pretty print of the key pair values.

Create a map

In Java, the Map interface is available in the java.util package. Import this package and create an example map with key pair values as shown below.

import java.util.*;

--------

Map<String, Integer> map = new HashMap<>();
map.put("John", 25);
map.put("Emma", 32);
map.put("Michael", 41);

Pretty print a map

To pretty print a map, we have to iterate over all the entries of a map and display the key-pair values.

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

In the above example, we used a for-each loop to iterate over the entries of the map. For each entry, we access the key and value using entry.getKey() and entry.getValue(). We then print the key-value pair in a formatted manner as shown below.

John: 25
Emma: 32
Michael: 41

References:

https://docs.oracle.com/javase/8/docs/api/java/util/Map.html

Categorized in:

Tagged in: