Pretty-print a Map in Java

Pretty-print a Map in Java

To pretty-print a Map in Java, you can use a loop to iterate through the map's entries and format them in a human-readable way. Here's an example of how to do it:

import java.util.*; public class MapPrettyPrint { public static void main(String[] args) { Map<String, Integer> map = new LinkedHashMap<>(); // LinkedHashMap to maintain order map.put("Alice", 30); map.put("Bob", 25); map.put("Charlie", 35); map.put("David", 28); prettyPrintMap(map); } public static void prettyPrintMap(Map<?, ?> map) { for (Map.Entry<?, ?> entry : map.entrySet()) { System.out.println(entry.getKey() + " -> " + entry.getValue()); } } } 

In this example, we create a Map named map and add some key-value pairs to it. Then, we call the prettyPrintMap method, which iterates through the map's entries using a for loop and prints each key-value pair in a formatted way.

The output will look like this:

Alice -> 30 Bob -> 25 Charlie -> 35 David -> 28 

You can customize the formatting in the prettyPrintMap method to match your specific requirements, such as using tabs, spaces, or other separators.


More Tags

amazon-web-services calc indexoutofboundsexception yii-extensions ipv6 ansi-c sling jradiobutton pygame-clock sql-delete

More Java Questions

More Chemical thermodynamics Calculators

More Investment Calculators

More Fitness-Health Calculators

More Mixtures and solutions Calculators