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

joining(delimiter): Adding Separators Between Elements

Using the single-argument joining(delimiter) to insert a separator (comma, space, etc.) between concatenated elements.

What You'll Learn

You'll learn how to use the single-argument joining(delimiter) collector to concatenate stream elements with a separator character or string between each element.

The Core Idea

While joining() with no arguments smashes all elements together into one continuous string, joining(delimiter) gives you control over what appears between each element. Think of it like assembling a grocery list: instead of "applesmilkbread", you want "apples, milk, bread" — the comma-space makes all the difference.

The delimiter can be any string: a comma, a space, a hyphen, even a multi-character separator like " | " or " -> ".

How It Works

The Collectors.joining(delimiter) method takes a single CharSequence argument (typically a String) that gets inserted between consecutive elements:

List<String> fruits = List.of("apple", "banana", "cherry");

String result = fruits.stream()
    .collect(Collectors.joining(", "));

System.out.println(result);
// Output: apple, banana, cherry

Notice how ", " appears between each fruit, but not before the first or after the last element.

Common Delimiters

List<String> words = List.of("Java", "Stream", "API");

// Space-separated
words.stream().collect(Collectors.joining(" "));
// Result: "Java Stream API"

// Hyphenated
words.stream().collect(Collectors.joining("-"));
// Result: "Java-Stream-API"

// Path-style
words.stream().collect(Collectors.joining("/"));
// Result: "Java/Stream/API"

Why This Matters

This is essential for generating CSV data, building file paths, creating formatted output, or any scenario where you need structured concatenation with consistent separators.

Key Takeaway: Collectors.joining(delimiter) inserts your specified separator string between each stream element during concatenation, giving you clean, readable results without manual string manipulation.