Skip to content

Instantly share code, notes, and snippets.

@tyb
Created July 22, 2019 09:47
Show Gist options
  • Save tyb/b94cd71aef354d2db7bc9466ae39c682 to your computer and use it in GitHub Desktop.
Save tyb/b94cd71aef354d2db7bc9466ae39c682 to your computer and use it in GitHub Desktop.
Pretty-print a Map in Java
//as json
new Gson().toJson(map)
//as json
ObjectMapper mapper = new ObjectMapper();
mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
//as json
Map<String, Object> stats = ...;
System.out.println(new JSONObject(stats).toString(2));
//fast
Arrays.toString(map.entrySet().toArray())
// Have a look at the Guava library:
Joiner.MapJoiner mapJoiner = Joiner.on(",").withKeyValueSeparator("=");
System.out.println(mapJoiner.join(map));
//Apache libraries to the rescue!
MapUtils.debugPrint(System.out, "myMap", map);
//using java8
map.forEach((key, value) -> System.out.println(key + ":" + value));
//with java 8 streams more verbose
Map<Object, Object> map = new HashMap<>();
String content = map.entrySet()
.stream()
.map(e -> e.getKey() + "=\"" + e.getValue() + "\"")
.collect(Collectors.joining(", "));
System.out.println(content);
//verbose
public class PrettyPrintingMap<K, V> {
private Map<K, V> map;
public PrettyPrintingMap(Map<K, V> map) {
this.map = map;
}
public String toString() {
StringBuilder sb = new StringBuilder();
Iterator<Entry<K, V>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Entry<K, V> entry = iter.next();
sb.append(entry.getKey());
sb.append('=').append('"');
sb.append(entry.getValue());
sb.append('"');
if (iter.hasNext()) {
sb.append(',').append(' ');
}
}
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment