Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Collectors.partitioningBy: practical reference

Collectors.partitioningBy: practical reference: Collectors.partitioningBy divides input into exactly two Boolean-keyed groups according to a predicate, with an optional downstream collector.

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

Syntax

Collectors.partitioningBy(...)

Collectors.partitioningBy divides input into exactly two Boolean-keyed groups according to a predicate, with an optional downstream collector.

Use it when the domain is a yes/no split and both partitions should be available without a second traversal.

The result is not a general grouping map: it always has true and false mappings. The returned map and its values have no blanket mutability guarantee.

For empty input both keys remain present with empty downstream results. Predicate exceptions propagate and stateful predicates are unsafe in parallel pipelines.

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 parts = java.util.stream.Stream.of(1, 2, 3, 4)
                .collect(java.util.stream.Collectors.partitioningBy(n -> n % 2 == 0));
        System.out.println(parts.get(false));
        System.out.println(parts.get(true));
    }
}

Result

[1, 3]
[2, 4]

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

Sources