Collectors.joining() in Java
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
// 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.
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".
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.
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(" | ", "[ ", " ]")));
}
}
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.
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);
}
}
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.
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()));
}
}
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.
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));
}
}
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
CharSequenceelements; map other types first. - Empty stream: returns prefix + suffix (or
""), nevernull. - 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
| Approach | Input | Delimiter | Prefix and suffix |
|---|---|---|---|
Collectors.joining(...) | Stream of CharSequence | Yes | Yes |
String.join(",", list) | Iterable or array of CharSequence | Yes | No |
new StringJoiner(",", "[", "]") | Added one by one | Yes | Yes |
reduce("", String::concat) | Stream of String | Manual | Manual; slow |
Without filtering or mapping, String.join() is the simplest choice for an existing list.
7. Common Mistakes and Best Practices
Concatenating with reduce()
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
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(", ")));
}
}
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()concatenatesCharSequenceelements into oneString.- 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
Frequently Asked Questions (FAQ)
Q1. What does Collectors.joining() do?
It returns a collector that concatenates the CharSequence elements of a stream into one String, optionally with a delimiter between elements and a prefix and suffix around the result.
Q2. How do I join a list of integers with commas?
Map the numbers to strings first: list.stream().map(String::valueOf).collect(Collectors.joining(",")).
Q3. What does joining() return for an empty stream?
It returns the prefix followed by the suffix, or an empty string when no prefix and suffix are given. It never returns null.
Q4. What is the difference between Collectors.joining() and String.join()?
String.join() joins an existing Iterable or array with a delimiter. Collectors.joining() works at the end of a stream pipeline, so you can filter and map first, and it also supports a prefix and suffix.
Q5. How does joining() handle null elements?
A null element is appended as the four characters null. Filter nulls with Objects::nonNull or map them to a default before joining.