Course contentsShow
← Java
Lesson 1562 of 2,87034. Collectors in DepthFree lesson

joining(delimiter, prefix, suffix): Full Control

Using the three-argument joining() to wrap the result with a prefix and suffix, useful for formatting lists or JSON arrays.

joining(delimiter, prefix, suffix): Full Control

You'll learn how to wrap your joined stream elements with custom prefix and suffix strings for complete formatting control.

When you need to format a collection of strings into a specific structure—like a JSON array, a SQL list, or a formatted report—the three-argument version of joining() gives you complete control. This variant lets you specify not just what goes between elements (the delimiter), but also what appears before the first element (prefix) and after the last element (suffix).

The Syntax

Collectors.joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)

How It Works

Think of it like building a sandwich: the delimiter is what separates your ingredients, but the prefix and suffix are the two slices of bread that wrap everything together. The collector applies the prefix first, then joins all elements with the delimiter, and finally adds the suffix at the end.

Common Use Cases

Creating JSON arrays:

List<String> fruits = List.of("apple", "banana", "cherry");
String json = fruits.stream()
    .collect(Collectors.joining("\", \"", "[\"", "\"]"));
// Result: ["apple", "banana", "cherry"]

Formatting SQL IN clauses:

List<Integer> ids = List.of(101, 102, 103);
String sql = ids.stream()
    .map(String::valueOf)
    .collect(Collectors.joining(", ", "WHERE id IN (", ")"));
// Result: WHERE id IN (101, 102, 103)

Creating formatted lists:

String formattedList = names.stream()
    .collect(Collectors.joining("; ", "Names: ", "."));
// Result: Names: Alice; Bob; Charlie.

Key Takeaway: Use joining(delimiter, prefix, suffix) when you need to wrap your joined elements in specific formatting—perfect for generating JSON arrays, SQL clauses, or any structured text output.