Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Streams and Functional

Collectors.partitioningBy() method

Reference for Java Collectors.partitioningBy(): split a stream into true and false groups with a Predicate, add a downstream collector and read both keys.

Collectors.partitioningBy(predicate) splits the elements of a stream into exactly two groups: those for which the predicate returns true and those for which it returns false. The result is a Map<Boolean, List<T>>.

It looks like a special case of groupingBy(), but with one important difference: the map always contains both keys, even when one of the groups is empty. That makes the result safe to read with get(true) and get(false) without null checks.

Java
Map<Boolean, List<Integer>> parts =
        numbers.stream().collect(Collectors.partitioningBy(n -> n % 2 == 0));
List<Integer> evens = parts.get(true);

Try it

Java Even and odd numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java With a downstream collector

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

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

static <T, D, A> Collector<T, ?, Map<Boolean, D>> partitioningBy(
        Predicate<? super T> predicate,
        Collector<? super T, A, D> downstream)
Name Description
predicate Tested against each element; decides the true or false group.
downstream Optional collector applied to each of the two groups. Defaults to toList().

Returns: a collector that produces a Map<Boolean, ...> with the keys false and true, both always present.

Usage notes

  • Both keys always exist. An empty input gives {false=[], true=[]}. With groupingBy() an empty group would simply be missing.
  • Printing order: the map prints false first, then true. The returned map is a small special-purpose implementation, but you should still read it by key rather than by position.
  • Only two groups. For three or more categories use groupingBy() with a classifier that returns an enum or a string.
  • Unmodifiable? Do not rely on being able to add keys to the map. Treat it as a read-only result.
  • Null elements are passed to the predicate as they are, so a predicate that dereferences them throws NullPointerException.
  • Single pass. The stream is traversed once, which is cheaper than calling filter() twice with opposite predicates.
  • Parallel streams work and keep each group's encounter order when the downstream collector does.