Java String.join
Combine multiple pieces of text using a literal delimiter between adjacent elements.
A simple example
String.join
- Start with a and b, separator -
- Do this Join using the separator
- Result a-b
class Main {
public static void main(String[] args) throws Exception {
System.out.println(String.join("-", "a", "b"));
}
}
a-b
Syntax
public static String join(CharSequence delimiter, CharSequence... elements)
JDK 21 method signatures (2)
public static String join(CharSequence delimiter, CharSequence... elements)
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaPrint a shopping list on one line
A display receives an ordered list of items as separate values. Join them into one readable line with separators between neighboring values and no extra separator after the last one.
class Main {
public static void main(String[] args) throws Exception {
System.out.println(String.join(", ", "rice", "tea", "oats"));
}
}
rice, tea, oats
Two separators connect three items.
Build a route from its stops
A transport planner stores stops as separate names. Produce a route caption with a separator only between adjacent stops so the printed sign has no dangling punctuation.
class Main {
public static void main(String[] args) throws Exception {
var stops = java.util.List.of("Home", "Campus", "Library");
System.out.println(String.join(" → ", stops));
}
}
Home → Campus → Library
The same arrow is inserted between each pair of consecutive stops.
Build a parcel shelf identifier
The shelf prefix already includes the hyphen. Combine the two fragments in order without adding another separator. What label goes to the printer?
What to watch for
Join inserts separators only between elements. Decide how missing or null items should be represented first.