A quick and easy way to join array elements with a separator (the opposite of split) in Java
To join array elements with a separator in Java, you can use the join
method from the String
class. This method was introduced in Java 8 and it allows you to join the elements of an array or an Iterable
object with a specified delimiter:
String[] elements = {"a", "b", "c"};
String result = String.join(",", elements); // "a,b,c"
If you are using an older version of Java that does not have the join
method, you can use a StringBuilder
to concatenate the elements with the separator:
String[] elements = {"a", "b", "c"};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < elements.length; i++) {
sb.append(elements[i]);
if (i < elements.length - 1) {
sb.append(",");
}
}
String result = sb.toString(); // "a,b,c"
You can also use the Collectors.joining
method from the java.util.stream.Collectors
class to join the elements of a stream:
String[] elements = {"a", "b", "c"};
String result = Arrays.stream(elements).collect(Collectors.joining(",")); // "a,b,c"
This is useful if you want to join the elements of a stream in a functional style.