Map to String in Java

前端 未结 2 883
感情败类
感情败类 2020-12-09 00:34

When I do System.out.println(map) in Java, I get a nice output in stdout. How can I obtain this same string representation of a Map in a variable w

相关标签:
2条回答
  • 2020-12-09 01:04

    Use Object#toString().

    String string = map.toString();
    

    That's after all also what System.out.println(object) does under the hoods. The format for maps is described in AbstractMap#toString().

    Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).

    0 讨论(0)
  • 2020-12-09 01:12

    You can also use google-collections (guava) Joiner class if you want to customize the print format

    0 讨论(0)
提交回复
热议问题