映射到 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:21:28  来源:igfitidea点击:

Map to String in Java

javamaptostring

提问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 Mapin 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().

使用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 entrySetview'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).

返回此地图的字符串表示形式。字符串表示由一系列键值映射组成,按映射entrySet视图的迭代器返回的顺序排列,括在大括号(“{}”)中。相邻的映射由字符“,”(逗号和空格)分隔。每个键值映射都呈现为键后跟等号 ("=") 后跟关联的值。键和值被转换为字符串 by String.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 类