Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Stream.collect: practical reference

Stream.collect: practical reference: Stream.collect is a terminal mutable reduction that accumulates elements into a container through a Collector or through supplier, accumulator, and combiner functions.

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

Syntax

Stream.collect(...)

Stream.collect is a terminal mutable reduction that accumulates elements into a container through a Collector or through supplier, accumulator, and combiner functions.

Use Collectors for lists, maps, grouping, and statistics, and the three-function overload for a custom mutable container.

In a parallel pipeline the combiner must merge partitions correctly; relying on one container, call order, or unsynchronized side effects is erroneous.

The operation consumes the stream; a null argument causes NullPointerException, and CONCURRENT and UNORDERED characteristics govern shared accumulation.

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 {
        var list = java.util.stream.Stream.of("a", "b").collect(java.util.stream.Collectors.toList());
        System.out.println(list);
    }
}

Result

[a, b]

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

Sources