Convert array of strings into a string in Java

arrays, java, string

Solution

Java 8+

Use `String.join()`:

String str = String.join(",", arr);

Note that `arr` can also be any `Iterable` (such as a list), not just an array.

If you have a `Stream`, you can use the joining collector:

Stream.of("a", "b", "c")
      .collect(Collectors.joining(","))

Legacy (Java 7 and earlier)

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);

Note that if you're really legacy (Java 1.4 and earlier) you'll need to replace `StringBuilder` there with `StringBuffer`.

Android

Use `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.

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.

Problem

I want the Java code for converting an array of strings into an string.

Original source

Related problems