问题描述
我想要将字符串数组转换为字符串的 Java 代码.
I want the Java code for converting an array of strings into an string.
推荐答案
Java 8+
使用String.join()
:
String str = String.join(",", arr);
请注意,arr
也可以是任何 Iterable
(例如列表),而不仅仅是数组.
Note that arr
can also be any Iterable
(such as a list), not just an array.
如果你有一个Stream
,你可以使用加入收集器:
If you have a Stream
, you can use the joining collector:
Stream.of("a", "b", "c")
.collect(Collectors.joining(","))
旧版(Java 7 及更早版本)
StringBuilder builder = new StringBuilder();
for(String s : arr) {
builder.append(s);
}
String str = builder.toString();
或者,如果您只想要调试风格"转储数组:
Alternatively, if you just want a "debug-style" dump of an array:
String str = Arrays.toString(arr);
请注意,如果您真的是旧版(Java 1.4 及更早版本),则需要将 StringBuilder
替换为 StringBuffer
.
Note that if you're really legacy (Java 1.4 and earlier) you'll need to replace StringBuilder
there with StringBuffer
.
使用TextUtils.join()
:
String str = TextUtils.join(",", arr);
一般注意事项
您可以根据字符串之间需要的字符(如果有)来修改上述所有示例.
General notes
You can modify all the above examples depending on what characters, if any, you want in between strings.
不要 使用字符串并在循环中使用 += 附加到它,就像此处显示的某些答案一样.这将 GC 发送到屋顶,因为您正在创建和丢弃与数组中的项目一样多的字符串对象.对于小数组,您可能不会真正注意到差异,但对于大数组,它可能会慢几个数量级.
DON'T use a string and just append to it with += in a loop like some of the answers show here. This sends the GC through the roof because you're creating and throwing away as many string objects as you have items in your array. For small arrays you might not really notice the difference, but for large ones it can be orders of magnitude slower.
这篇关于将字符串数组转换为Java中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!