How to join strings with a separator
Short answer
String.join() glues elements together with a separator:
void main() {
var names = List.of("Anna", "Oleg", "Boris");
IO.println(String.join(", ", names));
}Output:
Anna, Oleg, BorisNon-string values
String.join() accepts only strings. Convert numbers and objects to strings in a stream first and collect with Collectors.joining():
void main() {
var numbers = List.of(1, 2, 3);
String text = numbers.stream()
.map(String::valueOf)
.collect(Collectors.joining(" + "));
IO.println(text);
}Output:
1 + 2 + 3Prefix and suffix
joining() has a version with a start and an end:
void main() {
var tags = List.of("java", "sql");
IO.println(tags.stream().collect(Collectors.joining(", ", "[", "]")));
}Output:
[java, sql]Joining in a loop
If elements arrive one by one, use StringJoiner — it adds separators only between elements:
void main() {
var joiner = new StringJoiner(" | ");
for (int i = 1; i <= 3; i++) {
joiner.add("item " + i);
}
IO.println(joiner);
}Output:
item 1 | item 2 | item 3Common mistake
Concatenating strings with += in a big loop. Each += creates a new string and the code gets slow. Use StringBuilder for building strings in a loop:
void main() {
var builder = new StringBuilder();
for (int i = 0; i < 5; i++) {
builder.append(i);
}
IO.println(builder);
}Output:
01234Functions used in this recipe
- String.join() — Joins strings with a separator.
- Collectors.joining() — A collector that joins the strings of a stream into one.
- StringBuilder.append() — Adds a value to the end of a StringBuilder.