Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Collectors.partitioningBy()

Splits stream elements into two groups by a condition.

Available since: Java 8

Syntax

static <T> Collector<T, ?, Map<Boolean, List<T>>> partitioningBy(Predicate<? super T> predicate)

Parameters

ParameterTypeDescription
predicatePredicate<? super T>The partitioning condition.

Return value

Collector<T, ?, Map<Boolean, List<T>>>A collector into a map with the keys `false` and `true`.

Examples

Passed and failed:

void main() {
    Map<Boolean, List<Integer>> parts = Stream.of(45, 82, 67, 30, 91)
        .collect(Collectors.partitioningBy(score -> score >= 60));
    IO.println("passed: " + parts.get(true));
    IO.println("failed: " + parts.get(false));
}

Output:

passed: [82, 67, 91]
failed: [45, 30]

Notes

The result always has both keys, even if one group is empty. A collector can be passed as the second argument, for example Collectors.counting(). For more than two groups use groupingBy().

See also

Related recipes

In the tutorial

  • Grouping — Grouping stream elements in Java — Collectors.groupingBy, counts and sums per group, mapping, TreeMap and partitioningBy.

Thanks for reading!

Donate to the site — we work hard for you.