Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Collectors.joining: practical reference

Collectors.joining: practical reference: Collectors.joining concatenates CharSequence elements, optionally inserting a delimiter and surrounding the result with a prefix and suffix.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

Collectors.joining(...)

Collectors.joining concatenates CharSequence elements, optionally inserting a delimiter and surrounding the result with a prefix and suffix.

Use it for deterministic textual aggregation after mapping non-text elements to strings.

A null element is appended as the four characters null through StringJoiner.add. joining does not escape CSV, JSON, HTML, or SQL, so structured formats still need their own encoder.

For an empty stream, joining(delimiter, prefix, suffix) returns prefix followed by suffix. Without prefix and suffix it returns the empty string.

The example exercises the documented element in a small deterministic program and compares exact standard output.

Examples

public class Main {
    public static void main(String[] args) throws Exception {
        String text = java.util.stream.Stream.of("A", "B", "C")
                .collect(java.util.stream.Collectors.joining(",", "[", "]"));
        System.out.println(text);
    }
}

Result

[A,B,C]

The example exercises the documented element in a small deterministic program and compares exact standard output.

Sources