在Java中将整数数组转换为字符串的最佳方法
在 Java 中,我有一个整数数组。有没有一种快速的方法将它们转换为字符串?
IE int[] x = new int[] {3,4,5}
x toString() 应该产生“345”
In Java, I have an array of integers. Is there a quick way to convert them to a string?
I.E. int[] x = new int[] {3,4,5}
x toString() should yield "345"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
最简单的高性能方法可能是 StringBuilder:
如果您发现自己在多个地方执行此操作,您可能需要查看 Guava 的
Joiner
类 - 尽管我不相信您能够将它用于原始数组。编辑:如下所述,您可以使用Ints.join
为此。Simplest performant approach is probably StringBuilder:
If you find yourself doing this in multiple places, you might want to look at Guava's
Joiner
class - although I don't believe you'll be able to use it for primitive arrays. EDIT: As pointed out below, you can useInts.join
for this.更新
为了完整性,Java 8 Streams 解决方案,但它并不漂亮(像 vavr< /a> 会更短更快):
Update
For completeness the Java 8 Streams solution, but it isn't pretty (libraries like vavr would be shorter and faster):
尝试这样做 - 您必须导入 java.util.Arrays ,然后 -
其中 intArray 是您的整数数组。
Try with this - you have to
import java.util.Arrays
and then -Where intArray is your integer array.
您至少需要阅读一遍。
You need to read all once at least.
这是您可以做到的另一种方法。基本上只是创建一个 for 循环来访问整数数组中的每个元素并将其添加到字符串中。
This is another way you can do it. Basically just makes a for-loop that accesses every element in the integer array and adds it to the string.