00:00

Collectors.joining() in Java

Last updated:

Collectors.joining() is a static method of java.util.stream.Collectors, available since Java 8, that returns a Collector which concatenates a stream of CharSequence elements, usually Strings, into one String. Optional arguments add a delimiter between elements and a prefix and suffix around the whole result.

It is the stream way to build CSV lines, comma-separated lists, SQL fragments and log messages. This tutorial covers the three overloads, how to join non-string values, empty streams and nulls, and how it compares with String.join().

1. Syntax and Method Signatures

Collectors.java (API)
// java.util.stream.Collectors (Java 8)
static Collector<CharSequence, ?, String> joining()
static Collector<CharSequence, ?, String> joining(CharSequence delimiter)
static Collector<CharSequence, ?, String> joining(CharSequence delimiter,
                                                  CharSequence prefix,
                                                  CharSequence suffix)

The collector accepts CharSequence elements, so a Stream<Integer> must be mapped to strings first, for example with map(String::valueOf). The result is always a String, never null.

Usage
String csv = names.stream().collect(Collectors.joining(", ", "[", "]"));   // [Asha, Ravi, Meera]

2. How joining() Works

Internally, joining() uses a StringBuilder (or a StringJoiner when a delimiter is given), so it builds the result in one buffer instead of creating a new string for every element. For parallel streams, each thread builds its own buffer, and the buffers are merged in encounter order, so the result is the same as sequentially.

For an empty stream, the result is just the prefix followed by the suffix, for example "[]", or the empty string with no prefix and suffix. A null element is appended as the text "null".

joining() with a delimiter, prefix and suffix The strings red, green and blue are joined with the delimiter comma space, the prefix opening brace and the suffix closing brace, giving the single string with braces around red, green, blue. STREAM "red" "green" "blue" joining(", ", "{", "}") STRING "{red, green, blue}"
Figure 1: The delimiter goes between elements only; the prefix and suffix wrap the whole result, even when the stream is empty.

3. Java Examples

Example 1: The three forms (Java 9+)

Join a list of product codes without a separator, with commas, and as a bracketed list.

JoiningForms.java
import java.util.List;
import java.util.stream.Collectors;

public class JoiningForms {

    public static void main(String[] args) {
        List<String> codes = List.of("A1", "B2", "C3");

        System.out.println(codes.stream().collect(Collectors.joining()));
        System.out.println(codes.stream().collect(Collectors.joining(",")));
        System.out.println(codes.stream().collect(Collectors.joining(" | ", "[ ", " ]")));
    }
}
Output
A1B2C3
A1,B2,C3
[ A1 | B2 | C3 ]

How it works: The delimiter appears only between elements, so there is no trailing comma to remove, and the prefix and suffix are added once.

Example 2: Joining non-string values (Java 9+)

Build a CSV line from an order's numeric fields.

JoinNumbers.java
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class JoinNumbers {

    public static void main(String[] args) {
        List<Integer> quantities = List.of(3, 12, 7);

        String csv = quantities.stream()
                .map(String::valueOf)
                .collect(Collectors.joining(","));

        String range = IntStream.rangeClosed(1, 5)
                .mapToObj(Integer::toString)
                .collect(Collectors.joining("-"));

        System.out.println("CSV:   " + csv);
        System.out.println("Range: " + range);
    }
}
Output
CSV:   3,12,7
Range: 1-2-3-4-5

How it works: joining() only accepts CharSequence elements, so numbers are mapped to strings first. Primitive streams use mapToObj().

Example 3: Building a SQL IN clause (Java 9+)

Create the placeholder part of a prepared statement for a variable number of ids, and an empty clause when there are none.

SqlPlaceholders.java
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class SqlPlaceholders {

    static String inClause(List<Long> ids) {
        return Collections.nCopies(ids.size(), "?").stream()
                .collect(Collectors.joining(", ", "WHERE id IN (", ")"));
    }

    public static void main(String[] args) {
        System.out.println(inClause(List.of(101L, 205L, 309L)));
        System.out.println(inClause(List.of()));
    }
}
Output
WHERE id IN (?, ?, ?)
WHERE id IN ()

How it works: Each id becomes a ? placeholder, which keeps the query safe from SQL injection. Note the empty case: the prefix and suffix are still added, producing an invalid IN (), so real code should check for an empty list first.

Example 4: Joining inside groups (Java 16+)

List the team members of each project on one line.

TeamsPerProject.java
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class TeamsPerProject {

    record Assignment(String project, String member) { }

    public static void main(String[] args) {
        List<Assignment> assignments = List.of(
                new Assignment("Atlas", "Ira"), new Assignment("Nova", "Ken"),
                new Assignment("Atlas", "Lea"), new Assignment("Atlas", "Max"), new Assignment("Nova", "Oz"));

        Map<String, String> teams = assignments.stream()
                .collect(Collectors.groupingBy(Assignment::project, TreeMap::new,
                        Collectors.mapping(Assignment::member, Collectors.joining(", "))));

        teams.forEach((project, members) -> System.out.println(project + ": " + members));
    }
}
Output
Atlas: Ira, Lea, Max
Nova: Ken, Oz

How it works: mapping() extracts each member's name, and joining() reduces each group to a single string.

4. Real-World Use Cases

  • Exports: CSV or TSV lines from object fields.
  • Messages: "Missing fields: name, phone" in validation errors.
  • Queries: placeholder lists and column lists for SQL.
  • Reports: per-group summaries such as team members per project.

5. Important Points

  • Only CharSequence elements; map other types first.
  • Empty stream: returns prefix + suffix (or ""), never null.
  • Nulls become the text "null"; filter or replace them first.
  • Order: follows encounter order, also in parallel.
  • Escaping: joining() does not quote or escape values; real CSV with commas in values needs a CSV library.

6. joining() vs Other Ways to Join

ApproachInputDelimiterPrefix and suffix
Collectors.joining(...)Stream of CharSequenceYesYes
String.join(",", list)Iterable or array of CharSequenceYesNo
new StringJoiner(",", "[", "]")Added one by oneYesYes
reduce("", String::concat)Stream of StringManualManual; slow

Without filtering or mapping, String.join() is the simplest choice for an existing list.

7. Common Mistakes and Best Practices

Concatenating with reduce()

Wrong
String all = names.stream().reduce("", (a, b) -> a + "," + b);   // leading comma, new String per element

Use joining(","): no leading delimiter and one buffer for the whole result.

Joining values that contain nulls

JoinSkipNulls.java
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class JoinSkipNulls {

    public static void main(String[] args) {
        List<String> parts = Arrays.asList("Flat 4", null, "MG Road", "Bengaluru");

        System.out.println(parts.stream().collect(Collectors.joining(", ")));
        System.out.println(parts.stream().filter(Objects::nonNull).collect(Collectors.joining(", ")));
    }
}
Output
Flat 4, null, MG Road, Bengaluru
Flat 4, MG Road, Bengaluru

Other mistakes to avoid

  • Passing a Stream<Integer> directly; it does not compile.
  • Building SQL with values instead of placeholders.
  • Forgetting the empty case when a prefix and suffix are used.

8. Summary

  • joining() concatenates CharSequence elements into one String.
  • Overloads add a delimiter, and a prefix and suffix.
  • Map other types to strings first and filter out nulls.
  • An empty stream returns prefix + suffix, never null.

9. References