Joining Strings
Joining a list of values with a separator is a small task with a classic bug: the separator that ends up after the last item. Java 8 added String.join, StringJoiner and Collectors.joining to solve it. This page explains how they work, covers empty values, merging and nulls, builds CSV, SQL and URL strings correctly, and measures them against hand-written loops.
Contents
What joining does
Joining takes a sequence of strings and produces one string with a delimiter between each pair, optionally wrapped in a prefix and suffix. Three elements and the delimiter ", "a, b, c
Java 8 added three APIs for it. StringJoinerString.joinCollectors.joiningCharSequencenullnull
| API | Since | Prefix and suffix | Best for |
|---|---|---|---|
String.join(delimiter, elements) | Java 8 | No | A collection or varargs of strings |
StringJoiner | Java 8 | Yes, plus an empty value | Adding elements one by one in a loop |
Collectors.joining | Java 8 | Yes | The end of a stream pipeline |
StringBuilder | Java 5 | By hand | Custom rules per element; hot code |
List.toStringArrays.toString | Java 1.2, Java 5 | Always [] | Debugging output |
Guava JoinerStringUtils.join | Libraries | Varies | Projects that already use them, for options such as skipping nulls |
The programs were compiled and run on JDK 21.
The four ways side by side
Three short language names are enough to see the delimiter handling of each approach. The StringBuilder
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;
public class JoinWays {
public static void main(String[] args) {
List<String> langs = List.of("Java", "Go", "Rust");
// The manual way: the trailing separator has to be handled by hand
StringBuilder sb = new StringBuilder();
for (String l : langs) {
if (!sb.isEmpty()) {
sb.append(", ");
}
sb.append(l);
}
System.out.println("StringBuilder: " + sb);
// String.join: delimiter plus varargs or any Iterable
System.out.println("String.join: " + String.join(", ", langs));
System.out.println("join varargs: " + String.join("/", "usr", "local", "bin"));
// StringJoiner adds a prefix and suffix
StringJoiner sj = new StringJoiner(", ", "[", "]");
langs.forEach(sj::add);
System.out.println("StringJoiner: " + sj);
// Collectors.joining: the same three options at the end of a stream
String upper = langs.stream().map(String::toUpperCase)
.collect(Collectors.joining(" | ", "<", ">"));
System.out.println("Collectors.joining: " + upper);
}
}
Output:
StringBuilder: Java, Go, Rust
String.join: Java, Go, Rust
join varargs: usr/local/bin
StringJoiner: [Java, Go, Rust]
Collectors.joining: <JAVA | GO | RUST>
- The
loop adds the separator before every element except the first, checked withStringBuilder . Forgetting that check, or appending after every element, is the classic trailing-comma bug.isEmpty() takes a delimiter and either anString.join ofIterable , such as aCharSequence , or varargs, as inList<String> .usr/local/bin adds a prefix and suffix around the joined elements, givingStringJoiner .[Java, Go, Rust] has the same three options and fits afterCollectors.joining andmap , here uppercasing first.filter- A common workaround seen in older code,
followed by removing the brackets withlist.toString() orreplace , breaks as soon as an element itself contains a bracket or a comma. Any of the three join APIs is shorter and correct.substring
StringJoiner details: empty value, merge and length
StringJoiner
import java.util.StringJoiner;
public class JoinerDetails {
public static void main(String[] args) {
// setEmptyValue: what toString returns when nothing was added
StringJoiner tags = new StringJoiner(", ", "{", "}");
System.out.println("empty, default: " + tags + " length " + tags.length());
tags.setEmptyValue("(no tags)");
System.out.println("empty, custom: " + tags);
tags.add("new");
System.out.println("after one add: " + tags + " length " + tags.length());
tags.add("");
System.out.println("after add(\"\"): "
+ tags + " (empty strings still get a delimiter)");
// An empty value counts only while nothing was added
StringJoiner blank = new StringJoiner(",");
blank.setEmptyValue("EMPTY");
blank.add("");
System.out.println("add(\"\") then toString: [" + blank + "]");
// merge: append another joiner's content as one element, without its prefix and suffix
StringJoiner a = new StringJoiner(", ", "[", "]").add("x").add("y");
StringJoiner b = new StringJoiner("-", "(", ")").add("1").add("2");
System.out.println("merge: " + a.merge(b));
System.out.println("merging an empty joiner adds nothing: "
+ new StringJoiner(",").add("p").merge(new StringJoiner(";")));
// toString can be called repeatedly while adding
StringJoiner path = new StringJoiner("/", "/", "");
for (String part : new String[] {"usr", "local", "bin"}) {
path.add(part);
System.out.println(" so far: " + path);
}
}
}
Output:
empty, default: {} length 2
empty, custom: (no tags)
after one add: {new} length 5
after add(""): {new, } (empty strings still get a delimiter)
add("") then toString: []
merge: [x, y, 1-2]
merging an empty joiner adds nothing: p
so far: /usr
so far: /usr/local
so far: /usr/local/bin
- With nothing added, a joiner returns just its prefix and suffix,
, length 2.{} replaces that, which is useful for messages such as "no results".setEmptyValue("(no tags)") returns the length the result would have, including prefix and suffix, without building it.length()- An empty string is still an element, so
produces a delimiter followed by nothing:add("") .{new, } - The empty value applies only while nothing has been added. After
, the joiner is no longer empty, so the result is an empty string, notadd("") .EMPTY adds the other joiner's content as a single element, joined with its own delimiter but without its prefix and suffix, somerge appears inside1-2 . Merging an empty joiner adds nothing, not even a delimiter.[x, y, 1-2] can be called at any time, and adding more elements afterwards works, which the growing path shows.toString()
Nulls, numbers and other types
The join methods accept only CharSequencenull
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class NullsAndTypes {
public static void main(String[] args) {
// null elements become the text "null"
List<String> withNull = Arrays.asList("a", null, "c", " ");
System.out.println("String.join: " + String.join(",", withNull));
System.out.println("skip nulls/blanks: " + withNull.stream()
.filter(s -> s != null && !s.isBlank()).collect(Collectors.joining(",")));
System.out.println("replace nulls: " + withNull.stream()
.map(s -> Objects.toString(s, "-")).collect(Collectors.joining(",")));
// A null delimiter or list throws
try {
String.join(null, "a", "b");
} catch (NullPointerException e) {
System.out.println("null delimiter: NullPointerException");
}
// String.join needs CharSequence elements; other types must be mapped first
List<Integer> nums = List.of(3, 1, 4);
System.out.println("numbers: "
+ nums.stream().map(String::valueOf).collect(Collectors.joining("+")));
System.out.println("int range: "
+ IntStream.rangeClosed(1, 5).mapToObj(Integer::toString)
.collect(Collectors.joining(" ")));
System.out.println("List.toString: " + nums + " Arrays.toString: "
+ Arrays.toString(new int[] {3, 1, 4}));
// Map entries: choose the format of each entry
Map<String, Integer> stock = new TreeMap<>(Map.of("pen", 120, "ink", 8, "pad", 40));
System.out.println("map entries: " + stock.entrySet().stream()
.map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining("; ")));
// Characters of a string, separated
System.out.println("characters: " + "Java".chars().mapToObj(Character::toString)
.collect(Collectors.joining("-")));
// StringBuilder elements work with String.join, since they are CharSequences
System.out.println("CharSequence: "
+ String.join("|", new StringBuilder("x"), new StringBuilder("y")));
}
}
Output:
String.join: a,null,c,
skip nulls/blanks: a,c
replace nulls: a,-,c,
null delimiter: NullPointerException
numbers: 3+1+4
int range: 1 2 3 4 5
List.toString: [3, 1, 4] Arrays.toString: [3, 1, 4]
map entries: ink=8; pad=40; pen=120
characters: J-a-v-a
CharSequence: x|y
- A
element is written as the four lettersnull , and a blank string as its spaces. Filtering in the stream removes both, andnull replaces nulls with a placeholder.Objects.toString(s, "-") - A null delimiter, or a null list, throws
.NullPointerException - Numbers must be converted first.
works for any object stream, andmap(String::valueOf) for anmapToObj(Integer::toString) .IntStream andList.toString() already join withArrays.toString() inside brackets. That format is meant for debugging; build any format other programs depend on explicitly.", "- For a map, map each entry to the text you want, here
, then join. Akey=value makes the order predictable.TreeMap accepts anyString.join , soCharSequence elements work withoutStringBuilder .toString()
Joining into real formats: CSV, SQL, URLs and prose
Joining is often the last step in producing a format that another program parses. The inputs contain the characters that break each format: a comma and quotes in CSV fields, a space and &
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class RealFormats {
public static void main(String[] args) {
// CSV: fields that contain the delimiter or quotes must be quoted
List<String> fields = List.of("42", "Lovelace, Ada", "said \"hi\"", "London");
System.out.println("naive CSV: " + String.join(",", fields));
System.out.println("quoted CSV: " + fields.stream().map(RealFormats::csvField)
.collect(Collectors.joining(",")));
System.out.println("naive line splits into " + String.join(",", fields).split(",").length
+ " fields instead of " + fields.size());
// SQL IN clause: placeholders, never the values themselves
List<Long> ids = List.of(7L, 12L, 31L);
String sql = "SELECT * FROM orders WHERE id IN "
+ String.join(", ", Collections.nCopies(ids.size(), "?")).transform(s -> "(" + s + ")");
System.out.println(sql);
String sql2 = ids.stream().map(id -> "?")
.collect(Collectors.joining(", ", "SELECT * FROM orders WHERE id IN (", ")"));
System.out.println(sql2.equals(sql));
// URL query string: encode each key and value
Map<String, String> params = new LinkedHashMap<>();
params.put("q", "java joiner");
params.put("lang", "en&fr");
System.out.println("?" + params.entrySet().stream()
.map(e -> encode(e.getKey()) + "=" + encode(e.getValue()))
.collect(Collectors.joining("&")));
// A list for people: "a, b and c"
for (List<String> names : List.of(List.of("Ann"), List.of("Ann", "Bob"),
List.of("Ann", "Bob", "Cy"))) {
System.out.println("human list: " + humanList(names));
}
}
static String csvField(String f) {
if (f.contains(",") || f.contains("\"") || f.contains("\n")) {
return "\"" + f.replace("\"", "\"\"") + "\"";
}
return f;
}
static String encode(String s) {
return URLEncoder.encode(s, StandardCharsets.UTF_8);
}
static String humanList(List<String> names) {
if (names.size() <= 1) {
return String.join("", names);
}
return String.join(", ", names.subList(0, names.size() - 1)) + " and "
+ names.get(names.size() - 1);
}
}
Output:
naive CSV: 42,Lovelace, Ada,said "hi",London
quoted CSV: 42,"Lovelace, Ada","said ""hi""",London
naive line splits into 5 fields instead of 4
SELECT * FROM orders WHERE id IN (?, ?, ?)
true
?q=java+joiner&lang=en%26fr
human list: Ann
human list: Ann and Bob
human list: Ann, Bob and Cy
- Joining CSV fields with plain
breaks when a field contains a comma: the line splits back into 5 fields instead of 4. Fields with commas, quotes or line breaks must be wrapped in quotes, with inner quotes doubled, as RFC 4180 describes. Each element has to be escaped before joining.String.join - For a SQL
clause, join oneIN placeholder per value and bind the values through a? . Joining the values themselves into SQL invites SQL injection.PreparedStatement and the stream version produce the same text.Collections.nCopies - Query parameters need
on each key and value before joining withURLEncoder.encode , otherwise the& inside& would start a new parameter.en&fr - Lists for people need a different last separator, which no join method supports. Join all but the last element and add
by hand." and "
The general rule is that joining is only safe when no element can contain the delimiter. Either guarantee that, as with numeric IDs, or escape every element for the target format. For CSV, JSON, XML and SQL, a dedicated library or API does that escaping correctly in all cases, including line breaks, Unicode and empty values, and is the better choice for anything beyond simple data. Splitting such strings back apart is covered on the
Joining groups and parallel streams
Collectors.joininggroupingBy
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class GroupedJoin {
record Employee(String name, String dept) {
}
public static void main(String[] args) {
List<Employee> staff = List.of(new Employee("Zoe", "Sales"), new Employee("Ann", "IT"),
new Employee("Bob", "Sales"), new Employee("Cy", "IT"), new Employee("Dee", "HR"),
new Employee("Al", "Sales"));
Map<String, String> byDept = staff.stream().collect(Collectors.groupingBy(Employee::dept,
TreeMap::new, Collectors.mapping(Employee::name, Collectors.joining(", "))));
System.out.println("input order: " + byDept);
Map<String, String> sorted = staff.stream().collect(Collectors.groupingBy(Employee::dept,
TreeMap::new, Collectors.collectingAndThen(
Collectors.mapping(Employee::name, Collectors.toList()),
names -> names.stream().sorted().collect(Collectors.joining(", ")))));
System.out.println("sorted names: " + sorted);
Map<String, String> counted = staff.stream().collect(Collectors.groupingBy(Employee::dept,
TreeMap::new, Collectors.collectingAndThen(
Collectors.mapping(Employee::name, Collectors.joining(", ")),
joined -> joined + " (" + joined.split(", ").length + ")")));
System.out.println("with counts: " + counted);
String letters = IntStream.rangeClosed('a', 'z').parallel()
.mapToObj(c -> String.valueOf((char) c))
.collect(Collectors.joining());
System.out.println("parallel joining: " + letters);
}
}
Output:
input order: {HR=Dee, IT=Ann, Cy, Sales=Zoe, Bob, Al}
sorted names: {HR=Dee, IT=Ann, Cy, Sales=Al, Bob, Zoe}
with counts: {HR=Dee (1), IT=Ann, Cy (2), Sales=Zoe, Bob, Al (3)}
parallel joining: abcdefghijklmnopqrstuvwxyz
turns each department's employees into one string. ThegroupingBy(Employee::dept, TreeMap::new, mapping(Employee::name, joining(", "))) sorts the departments, and the names keep the order of the input list.TreeMap- To sort the names inside each group, sort the stream first, or collect to a list and sort before joining, as the second map does.
wraps the joined text, here adding the number of people, without a second pass over the map.collectingAndThen- A parallel stream splits the work across threads, but
combines the partial results in encounter order, so the 26 letters came out in order. Ajoining that appends to a sharedforEach from a parallel stream has no such guarantee and is not thread-safe.StringBuilder
More grouping patterns are on the
How fast is each approach?
The program joins a million short strings with each API, then compares String.join
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
import java.util.function.Function;
import java.util.stream.Collectors;
public class JoinSpeed {
public static void main(String[] args) {
List<String> words = new ArrayList<>();
for (int i = 0; i < 1000000; i++) {
words.add("w" + i);
}
System.out.printf("join %,d short strings with \", \"%n", words.size());
time("String.join", words, w -> String.join(", ", w));
time("StringJoiner", words, w -> {
StringJoiner j = new StringJoiner(", ");
w.forEach(j::add);
return j.toString();
});
time("Collectors.joining", words, w -> w.stream().collect(Collectors.joining(", ")));
time("StringBuilder loop", words, w -> {
StringBuilder sb = new StringBuilder();
for (String s : w) {
if (!sb.isEmpty()) {
sb.append(", ");
}
sb.append(s);
}
return sb.toString();
});
List<String> few = words.subList(0, 20000);
System.out.printf("%njoin %,d strings%n", few.size());
time("String.join", few, w -> String.join(", ", w));
time("reduce with +", few, w -> w.stream().reduce((a, b) -> a + ", " + b).orElse(""));
time("+= in a loop", few, w -> {
String s = "";
for (String x : w) {
s += s.isEmpty() ? x : ", " + x;
}
return s;
});
}
// Best of 3 runs
static void time(String name, List<String> w, Function<List<String>, String> f) {
long best = Long.MAX_VALUE;
int length = 0;
for (int run = 0; run < 3; run++) {
long t0 = System.nanoTime();
length = f.apply(w).length();
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf(" %-20s %7.1f ms length %,d%n", name, best / 1e6, length);
}
}
Output (rough comparison, 2-CPU Linux, JDK 21):
join 1,000,000 short strings with ", "
String.join 23.2 ms length 8,888,888
StringJoiner 44.8 ms length 8,888,888
Collectors.joining 30.3 ms length 8,888,888
StringBuilder loop 35.3 ms length 8,888,888
join 20,000 strings
String.join 1.4 ms length 148,888
reduce with + 217.6 ms length 148,888
+= in a loop 206.7 ms length 148,888
,String.join andStringJoiner were all within a few tens of milliseconds for a million elements. The hand-writtenCollectors.joining loop landed in the same range, and which approach came first changed from run to run, so the choice is about readability.StringBuilder andreduce((a, b) -> a + ", " + b) in a loop both copy the growing string at every step. On only 20,000 elements they were more than a hundred times slower than+= , and the gap grows with the square of the size.String.join
Never build a joined string with reduce++=
Which one to use
| Situation | Use |
|---|---|
| A list or array of strings | String.join(", ", list) |
| A fixed set of values | String.join("/", a, b, c) |
| The end of a stream | Collectors.joining(", ", "[", "]") |
| Adding elements in a loop, with brackets | StringJoiner |
| Special text when there are no elements | StringJoiner.setEmptyValue |
| Numbers or other objects | map(String::valueOf)joining |
| Skip nulls or blanks | filter |
| CSV, URLs or other parsed formats | Escape or encode each element, then join |
SQL IN | Join ? |
| Different rules per element | A StringBuilder |