映射到 Java 中的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2828252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Map to String in Java
提问by Dan
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 without meddling with standard output? Something like String mapAsString = Collections.toString(map)
?
当我System.out.println(map)
使用 Java 时,我在 stdout 中得到了不错的输出。如何Map
在不干预标准输出的情况下获得变量中 a 的相同字符串表示?像String mapAsString = Collections.toString(map)
什么?
采纳答案by BalusC
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()
.
所有的亦是在此之后是System.out.println(object)
做头套下。地图的格式在 中描述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 byString.valueOf(Object)
.
返回此地图的字符串表示形式。字符串表示由一系列键值映射组成,按映射
entrySet
视图的迭代器返回的顺序排列,括在大括号(“{}”)中。相邻的映射由字符“,”(逗号和空格)分隔。每个键值映射都呈现为键后跟等号 ("=") 后跟关联的值。键和值被转换为字符串 byString.valueOf(Object)
。
回答by Aravind Yarram
You can also use google-collections (guava) Joiner class if you want to customize the print format
如果要自定义打印格式,也可以使用 google-collections (guava) Joiner 类