I am looking for a nice way to pretty-print a Map
.
map.toString()
gives me: {key1=value1, key2=value2, key3=value3}
I
I guess something like this would be cleaner, and provide you with more flexibility with the output format (simply change template):
String template = "%s=\"%s\",";
StringBuilder sb = new StringBuilder();
for (Entry e : map.entrySet()) {
sb.append(String.format(template, e.getKey(), e.getValue()));
}
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1); // Ugly way to remove the last comma
}
return sb.toString();
I know having to remove the last comma is ugly, but I think it's cleaner than alternatives like the one in this solution or manually using an iterator.
Using Java 8 Streams:
Map<Object, Object> map = new HashMap<>();
String content = map.entrySet()
.stream()
.map(e -> e.getKey() + "=\"" + e.getValue() + "\"")
.collect(Collectors.joining(", "));
System.out.println(content);
I prefer to convert the map to a JSON string it is:
supports nested complex types within the object
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public static String getAsFormattedJsonString(Object object)
{
ObjectMapper mapper = new ObjectMapper();
try
{
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
}
catch (JsonProcessingException e)
{
e.printStackTrace();
}
return "";
}
Apache libraries to the rescue!
MapUtils.debugPrint(System.out, "myMap", map);
All you need Apache commons-collections library (project link)
Maven users can add the library using this dependency:
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>