Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Stream.distinct: practical reference

Stream.distinct: practical reference: Stream.distinct is a stateful intermediate operation that removes duplicates according to Object.equals.

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

Syntax

Stream.distinct(...)

Stream.distinct is a stateful intermediate operation that removes duplicates according to Object.equals.

Use it when uniqueness belongs inside a lazy pipeline and the element type defines equals and hashCode correctly.

For an ordered stream it preserves the first duplicate representative, but in parallel it requires a full barrier and substantial buffering.

For an unordered source representative selection is not stable; null can remain as one distinct element, and processing starts only under a terminal operation.

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("a", "b", "a").distinct().toList();
        System.out.println(result);
    }
}

Result

[a, b]

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

Sources