Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Collectors.toSet: practical reference

Collectors.toSet: practical reference: Collectors.toSet accumulates elements into a Set and therefore removes duplicates, but it does not guarantee set type, order, mutability, serializability, or thread safety.

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

Syntax

Collectors.toSet(...)

Collectors.toSet accumulates elements into a Set and therefore removes duplicates, but it does not guarantee set type, order, mutability, serializability, or thread safety.

Use it when uniqueness matters and encounter order is not part of the required result contract.

Do not rely on HashSet identity or iteration order. The collector is UNORDERED, and parallel execution may expose assumptions about order.

An empty stream returns an empty set. Whether null is accepted is not promised by the collector contract and should not be relied upon.

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 set = java.util.stream.Stream.of("a", "b", "a")
                .collect(java.util.stream.Collectors.toSet());
        System.out.println(set.size());
        System.out.println(set.contains("a"));
    }
}

Result

2
true

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

Sources