Don't rely on the method toString()
as it is an implementation detail that could change from one version of Java to another, you should rather implement your own method.
Assuming that you use Java 8, it could be:
public static <K, V> String mapToString(Map<K, V> map) {
return map.entrySet()
.stream()
.map(entry -> entry.getKey() + ":" + entry.getValue())
.collect(Collectors.joining(", ", "{", "}"));
}
If you want to have the exact same implementation as AbstractMap#toString()
that checks if the key or the value is the current map, the code would then be:
public static <K, V> String mapToString(Map<K, V> map) {
return map.entrySet()
.stream()
.map(
entry -> (entry.getKey() == map ? "(this Map)" : entry.getKey())
+ ":"
+ (entry.getValue() == map ? "(this Map)" : entry.getValue()))
.collect(Collectors.joining(", ", "{", "}"));
}