How can I join a String array with a separator in Java?

I’m looking for a quick and easy way to perform the opposite of split, so that ["a", "b", "c"] becomes "a,b,c". Manually iterating through the array requires handling the last separator separately.

Is there a built-in or efficient join string array method in Java (perhaps in Apache Commons or Java standard library) that simplifies this?

If you’re using Java 8 or later, the easiest way to join a string array with a separator is by using String.join(). It’s built into the standard library and avoids unnecessary loops.

String[] words = {"a", "b", "c"};
String result = String.join(",", words);
System.out.println(result); // Output: a,b,c

This is probably the cleanest and most efficient way when working with arrays. It’s readable, fast, and avoids manual string concatenation issues.

The first approach is great, but if you’re working with streams and want more flexibility, Collectors.joining() is a solid alternative:

import java.util.Arrays;
import java.util.stream.Collectors;

String[] words = {"a", "b", "c"};
String result = Arrays.stream(words)
                      .collect(Collectors.joining(","));
System.out.println(result); // Output: a,b,c

Why use this?

If you need extra formatting (like adding a prefix or suffix), Collectors.joining(“,”, “[”, “]”) is useful. This approach works well for lists, too, not just arrays!

If you’re working on a project that already uses Apache Commons Lang, there’s no reason to reinvent the wheel. Just use StringUtils.join():

import org.apache.commons.lang3.StringUtils;

String[] words = {"a", "b", "c"};
String result = StringUtils.join(words, ",");
System.out.println(result); // Output: a,b,c

This is great because StringUtils.join() works seamlessly with different types of collections and handles null values gracefully. If your project already has Commons Lang, this is an easy win.