Java Reference ยท java.lang
Java String.join() method
Reference for Java String.join(): glue strings or an Iterable together with a delimiter, handle nulls and numbers, and compare it with Collectors.joining().
String.join() concatenates several strings with a delimiter between each pair. It was added in Java 8 and replaces the old loop that appended a separator and then had to trim the last one. You can pass the pieces directly as arguments, as an array, or as any Iterable of strings such as a List<String>.
It joins text only. Numbers and other objects must be converted first, usually with a stream and map(String::valueOf).
String path = String.join("/", "usr", "local", "bin"); // "usr/local/bin"
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public static String join(CharSequence delimiter, CharSequence... elements) public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
| Name | Description |
|---|---|
delimiter |
The text placed between elements. Can be empty. |
elements |
The pieces to join: a varargs list, an array, or an Iterable of CharSequence (String, StringBuilder and so on). |
Returns: the joined String. No elements gives ""; one element gives that element alone, with no delimiter.
Throws: NullPointerException if delimiter or elements is null.
Usage notes
nullelements become"null". The delimiter itself and theelementsargument must not benull, but items inside may be; filter them out first if you do not want that text.- Strings only.
String.join(",", List.of(1, 2))does not compile becauseIntegeris not aCharSequence. Map to strings first. - No prefix or suffix. If you need
[a, b], either add the brackets yourself, or useCollectors.joining(", ", "[", "]")or aStringJoiner. - Varargs ambiguity. Passing a
String[]uses it as the element array; passing a singleStringjoins just that one string. - Cost. Linear in the total length. Internally the result is built in one allocation of the right size, so it is faster than a naive
+=loop. - Inverse operation:
split()turns the joined text back into pieces, but only when the delimiter does not occur inside the data. - CSV caution. Joining with a comma does not quote values that contain commas or quotes; use a real CSV writer for that.