I am looking for a nice way to pretty-print a Map
.
map.toString()
gives me: {key1=value1, key2=value2, key3=value3}
I
Arrays.toString(map.entrySet().toArray())
String result = objectMapper.writeValueAsString(map)
- as simple as this!
Result:
{"2019-07-04T03:00":1,"2019-07-04T04:00":1,"2019-07-04T01:00":1,"2019-07-04T02:00":1,"2019-07-04T13:00":1,"2019-07-04T06:00":1 ...}
P.S. add Jackson JSON to your classpath.
Simple and easy. Welcome to the JSON world. Using Google's Gson:
new Gson().toJson(map)
Example of map with 3 keys:
{"array":[null,"Some string"],"just string":"Yo","number":999}
When I have org.json.JSONObject
in the classpath, I do:
Map<String, Object> stats = ...;
System.out.println(new JSONObject(stats).toString(2));
(this beautifully indents lists, sets and maps which may be nested)
Since java 8 there is easy way to do it with Lambda:
yourMap.keySet().forEach(key -> {
Object obj = yourMap.get(key);
System.out.println( obj);
}
public void printMapV2 (Map <?, ?> map) {
StringBuilder sb = new StringBuilder(128);
sb.append("{");
for (Map.Entry<?,?> entry : map.entrySet()) {
if (sb.length()>1) {
sb.append(", ");
}
sb.append(entry.getKey()).append("=").append(entry.getValue());
}
sb.append("}");
System.out.println(sb);
}