Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Collectors.collectingAndThen: practical reference

Collectors.collectingAndThen: practical reference: Collectors.collectingAndThen adapts a downstream collector and applies a finishing function exactly once to its completed result; the returned collector does not retain IDENTITY_FINISH.

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

Syntax

Collectors.collectingAndThen(...)

Collectors.collectingAndThen adapts a downstream collector and applies a finishing function exactly once to its completed result; the returned collector does not retain IDENTITY_FINISH.

Use it when collection and final representation belong in one reduction, for example collecting a mutable list and exposing an unmodifiable copy.

The finisher runs after accumulation, not once per element. Do not infer the downstream collector characteristics unchanged, because IDENTITY_FINISH is removed.

An empty stream still produces the downstream collector empty result and passes it to the finisher; exceptions thrown by the finisher propagate.

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 result = java.util.stream.Stream.of(3, 1, 2)
                .collect(java.util.stream.Collectors.collectingAndThen(
                    java.util.stream.Collectors.toList(), java.util.List::copyOf));
        System.out.println(result);
        try { result.add(4); } catch (UnsupportedOperationException error) { System.out.println("unmodifiable"); }
    }
}

Result

[3, 1, 2]
unmodifiable

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

Sources