很好地打印 Java 集合(toString 不返回漂亮的输出)
我希望像 Eclipse 调试器那样打印 Stack
对象(即 [1,2,3...]
),但使用 out = "output:" + stack
不会返回这个好的结果。
只是为了澄清一下,我正在谈论 Java 的内置集合,因此我无法重写其 toString()
。
如何获得堆栈的精美可打印版本?
I wish to print a Stack<Integer>
object as nicely as the Eclipse debugger does (i.e. [1,2,3...]
) but printing it with out = "output:" + stack
doesn't return this nice result.
Just to clarify, I'm talking about Java's built-in collection so I can't override its toString()
.
How can I get a nice printable version of the stack?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(20)
您可以将其转换为数组,然后使用 Arrays.toString(Object[]) 打印出来:
You could convert it to an array and then print that out with
Arrays.toString(Object[])
:(Java 8)
(Java 8)
使用 java 8 流和收集器可以轻松完成:
首先我们使用
map
和Object::toString
来创建Collection
,然后使用连接收集器以,
作为分隔符连接集合中的每个项目。With java 8 streams and collectors it can be done easily:
first we use
map
withObject::toString
to createCollection<String>
and then use joining collector to join every item in collection with,
as delimiter.Apache Commons 项目提供的 MapUtils 类提供了一个 MapUtils.debugPrint 方法,可以漂亮地打印您的地图。
The MapUtils class offered by the Apache Commons project offers a
MapUtils.debugPrint
method which will pretty print your map.番石榴看起来是一个不错的选择:
Iterables.toString(myIterable)
Guava looks like a good option:
Iterables.toString(myIterable)
System.out.println(Collection c) 已经以可读格式打印任何类型的集合。 仅当集合包含用户定义的对象时,才需要在用户定义的类中实现 toString() 来显示内容。
System.out.println(Collection c) already print any type of collection in readable format. Only if collection contains user defined objects , then you need to implement toString() in user defined class to display content.
在类上实现 toString()。
我推荐 Apache Commons ToStringBuilder 使这变得更容易。 有了它,您只需编写这种方法:
为了获得这种输出:
还有一个 反射实现。
Implement toString() on the class.
I recommend the Apache Commons ToStringBuilder to make this easier. With it, you just have to write this sort of method:
In order to get this sort of output:
There is also a reflective implementation.
我同意上面关于在您自己的类上覆盖
toString()
的评论(以及尽可能自动化该过程)。对于您没有定义的类,您可以为您想要根据自己的喜好处理的每个库类编写一个带有重载方法的
ToStringHelper
类:编辑:响应xukxpvfzflbbld 的评论,这是前面提到的情况的可能实现。
这不是一个完整的实现,而只是一个开始。
I agree with the above comments about overriding
toString()
on your own classes (and about automating that process as much as possible).For classes you didn't define, you could write a
ToStringHelper
class with an overloaded method for each library class you want to have handled to your own tastes:EDIT: Responding to the comment by xukxpvfzflbbld, here's a possible implementation for the cases mentioned previously.
This isn't a full-blown implementation, but just a starter.
您可以使用 JAVA 中的“Objects”类(自 1.7 起可用)
输出:1273, 123, 876, 897
另一种可能性是使用 Google Guave 中的“MoreObjects”类< /strong>,它提供了许多有用的辅助函数:
输出:
NameOfYourObject=[1273, 123, 876, 897]
番石榴文档
You can use the "Objects" class from JAVA (which is available since 1.7)
Output: 1273, 123, 876, 897
Another possibility is to use the "MoreObjects" class from Google Guave, which provides many of useful helper functions:
Output:
NameOfYourObject=[1273, 123, 876, 897]
Guava docs
使用Apache Commons 3,您想要调用
With Apache Commons 3, you want to call
在Java8
或
In Java8
or
如今,大多数集合在 Java 中(Java7/8)都有一个有用的
toString()
。因此,无需执行流操作来连接您需要的内容,只需覆盖集合中值类的
toString
即可获得您需要的内容。AbstractMap 和 < a href="https://docs.oracle.com/javase/8/docs/api/java/util/AbstractCollection.html#toString--" rel="nofollow noreferrer">AbstractCollection 实现 toString()通过对每个元素调用 toString 。
下面是一个显示行为的测试类。
更新 Java 14(2020 年 3 月)
如果您的类仅保存数据,记录现在是一项预览功能,不需要您重写
toString()
。 记录实现了数据契约,允许公众对其字段进行只读访问,并实现默认函数以方便您使用,例如比较、toString 和 hashcode。因此,一旦可以实现
Foo
,其行为如下:most collections have a useful
toString()
in java these days (Java7/8).So there is no need to do stream operations to concatenate what you need, just override
toString
of your value class in the collection and you get what you need.both AbstractMap and AbstractCollection implement toString() by calling toString per element.
below is a testclass to show behaviour.
Update Java 14 (Mar 2020)
Records are now a preview feature not requiring you to override
toString()
if your class only holds data. Records implement a data contract, giving public readonly access to it's fields and implementing default functions for your convience, like comparison, toString and hashcode.so once could implement
Foo
as follows with the behavior:较新的 JDK 已经实现了
AbstractCollection.toString()
,并且Stack
扩展了AbstractCollection
,因此您只需调用toString()
代码> 在您的收藏中:Newer JDK already has
AbstractCollection.toString()
implemented, andStack
extendsAbstractCollection
so you just have to calltoString()
on your collection:如果这是您自己的集合类而不是内置集合类,则需要重写其 toString 方法。 Eclipse 会为任何没有硬连线格式的对象调用该函数。
If this is your own collection class rather than a built in one, you need to override its toString method. Eclipse calls that function for any objects for which it does not have a hard-wired formatting.
只是修改了前面的示例以打印包含用户定义对象的集合。
Just Modified the previous example to print even collection containing user defined objects.
在 Collection 上调用 Sop 时要小心,它可能会抛出 ConcurrentModification 异常。 因为每个 Collection 的内部
toString
方法内部都会调用 Collection 上的Iterator
。Be careful when calling Sop on Collection, it can throw
ConcurrentModification
Exception. Because internallytoString
method of each Collection internally callsIterator
over the Collection.应该适用于除
Map
之外的任何集合,但它也很容易支持。如果需要,修改代码以将这 3 个字符作为参数传递。
Should work for any collection except
Map
, but it's easy to support, too.Modify code to pass these 3 chars as arguments if needed.
您可以尝试使用
You can try using
有两种方法可以简化您的工作。
1.导入Gson库。
2.使用龙目岛。
它们都可以帮助您从对象实例创建字符串。 Gson将解析你的对象,lombok将重写你的类对象的toString方法。
我举了一个关于 Gson PrettyPrint 的例子,我创建了辅助类来打印对象和对象集合。 如果您使用 lombok,您可以将您的类标记为 @ToString 并直接打印您的对象。
}
There are two ways you could simplify your work.
1. import Gson library.
2. use Lombok.
Both of them help you create String from object instance. Gson will parse your object, lombok will override your class object toString method.
I put an example about Gson prettyPrint, I create helper class to print object and collection of objects. If you are using lombok, you could mark your class as @ToString and print your object directly.
}
JSON
另一种解决方案可以将您的集合转换为 JSON 格式并打印Json 字符串。 优点是格式良好且可读的对象字符串,无需实现 toString() 。
使用 Google 的 Gson 的示例:
JSON
An alternative Solution could be converting your collection in the JSON format and print the Json-String. The advantage is a well formatted and readable Object-String without a need of implementing the
toString()
.Example using Google's Gson: