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 ", " give a, b, c: the delimiter appears two times, never at the end.

Java 8 added three APIs for it. StringJoiner is the general one, which you add elements to one at a time. String.join is a one-call shortcut for strings you already have in a collection or array, and Collectors.joining is the same operation at the end of a stream. All three accept only CharSequence elements, write null elements as the text null, and build the result once at the end, so their cost grows in proportion to the total length.

Ways to join strings
APISincePrefix and suffixBest for
String.join(delimiter, elements)Java 8NoA collection or varargs of strings
StringJoinerJava 8Yes, plus an empty valueAdding elements one by one in a loop
Collectors.joiningJava 8YesThe end of a stream pipeline
StringBuilder loopJava 5By handCustom rules per element; hot code
List.toString, Arrays.toStringJava 1.2, Java 5Always [ and ]Debugging output
Guava Joiner, Commons StringUtils.joinLibrariesVariesProjects 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 version shows the bookkeeping that the other three do for you.

Java
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:

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 StringBuilder loop adds the separator before every element except the first, checked with isEmpty(). Forgetting that check, or appending after every element, is the classic trailing-comma bug.
  • String.join takes a delimiter and either an Iterable of CharSequence, such as a List<String>, or varargs, as in usr/local/bin.
  • StringJoiner adds a prefix and suffix around the joined elements, giving [Java, Go, Rust].
  • Collectors.joining has the same three options and fits after map and filter, here uppercasing first.
  • A common workaround seen in older code, list.toString() followed by removing the brackets with replace or substring, breaks as soon as an element itself contains a bracket or a comma. Any of the three join APIs is shorter and correct.

StringJoiner details: empty value, merge and length

StringJoiner has a few behaviours that are easy to get wrong, especially around empty input. Each line of the program tests one of them.

Java
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:

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. setEmptyValue("(no tags)") replaces that, which is useful for messages such as "no results".
  • length() returns the length the result would have, including prefix and suffix, without building it.
  • An empty string is still an element, so add("") produces a delimiter followed by nothing: {new, }.
  • The empty value applies only while nothing has been added. After add(""), the joiner is no longer empty, so the result is an empty string, not EMPTY.
  • merge adds the other joiner's content as a single element, joined with its own delimiter but without its prefix and suffix, so 1-2 appears inside [x, y, 1-2]. Merging an empty joiner adds nothing, not even a delimiter.
  • toString() can be called at any time, and adding more elements afterwards works, which the growing path shows.

Nulls, numbers and other types

The join methods accept only CharSequence elements and treat null in a way that is rarely wanted. The inputs include a null, a blank string, integers, a map and the characters of a word.

Java
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:

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 null element is written as the four letters null, and a blank string as its spaces. Filtering in the stream removes both, and Objects.toString(s, "-") replaces nulls with a placeholder.
  • A null delimiter, or a null list, throws NullPointerException.
  • Numbers must be converted first. map(String::valueOf) works for any object stream, and mapToObj(Integer::toString) for an IntStream.
  • List.toString() and Arrays.toString() already join with ", " 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 key=value, then join. A TreeMap makes the order predictable.
  • String.join accepts any CharSequence, so StringBuilder elements work without 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 & in URL values.

Java
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:

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 String.join 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.
  • For a SQL IN clause, join one ? placeholder per value and bind the values through a PreparedStatement. Joining the values themselves into SQL invites SQL injection. Collections.nCopies and the stream version produce the same text.
  • Query parameters need URLEncoder.encode on each key and value before joining with &, otherwise the & inside en&fr would start a new parameter.
  • Lists for people need a different last separator, which no join method supports. Join all but the last element and add " and " by hand.

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 split page and the tokenizing page.

Joining groups and parallel streams

Collectors.joining is also a downstream collector, so it can join the values inside each group of a groupingBy. The data is a list of employees in three departments, and the second half checks that a parallel stream still joins in encounter order.

Java
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:

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
  • groupingBy(Employee::dept, TreeMap::new, mapping(Employee::name, joining(", "))) turns each department's employees into one string. The TreeMap sorts the departments, and the names keep the order of the input list.
  • 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.
  • collectingAndThen wraps the joined text, here adding the number of people, without a second pass over the map.
  • A parallel stream splits the work across threads, but joining combines the partial results in encounter order, so the 26 letters came out in order. A forEach that appends to a shared StringBuilder from a parallel stream has no such guarantee and is not thread-safe.

More grouping patterns are on the groupingBy page.

How fast is each approach?

The program joins a million short strings with each API, then compares String.join with two quadratic approaches on 20,000 strings. The best time of three runs is printed for each approach.

Java
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):

Output
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, StringJoiner and Collectors.joining were all within a few tens of milliseconds for a million elements. The hand-written StringBuilder loop landed in the same range, and which approach came first changed from run to run, so the choice is about readability.
  • reduce((a, b) -> a + ", " + b) and += 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 String.join, and the gap grows with the square of the size.

Never build a joined string with reduce and +; it is the stream equivalent of += in a loop. See StringBuilder for why.

Which one to use

Choosing a way to join
SituationUse
A list or array of stringsString.join(", ", list)
A fixed set of valuesString.join("/", a, b, c)
The end of a streamCollectors.joining(", ", "[", "]")
Adding elements in a loop, with bracketsStringJoiner
Special text when there are no elementsStringJoiner.setEmptyValue
Numbers or other objectsmap(String::valueOf), then joining
Skip nulls or blanksfilter in the stream first
CSV, URLs or other parsed formatsEscape or encode each element, then join
SQL IN listsJoin ? placeholders and bind the values
Different rules per elementA StringBuilder loop