Course contentsShow
← Java
Lesson 1582 of 2,87034. Collectors in DepthFree lesson

partitioningBy with Downstream Collectors

Use the two-argument form partitioningBy(predicate, downstream) to transform each partition, like counting or summing instead of collecting to lists.

partitioningBy with Downstream Collectors

What You'll Learn

You'll learn how to use partitioningBy with a downstream collector to transform each partition into something other than a list—like counts, sums, or custom collections.

The Core Idea

By default, partitioningBy(predicate) gives you a Map<Boolean, List<T>> where each partition is a list. But what if you don't need the full list? What if you just want to count how many items are in each partition, or sum their values, or collect them into a different structure?

The two-argument form partitioningBy(predicate, downstream) lets you specify a downstream collector that processes each partition's elements. Instead of collecting to lists, you can apply any collector you've learned—like counting(), summingInt(), averagingDouble(), or even toSet().

The Syntax

Collectors.partitioningBy(predicate, downstreamCollector)

The downstream collector operates on each partition independently, transforming the stream of elements in that partition into the final result you want.

Think of It This Way

Imagine sorting mail into two bins: "local" and "non-local." Basic partitioning gives you two bins full of letters. But with a downstream collector, you can say: "Don't give me the letters—just tell me how many are in each bin" or "Give me the total weight in each bin."

Common Examples

  • partitioningBy(isEven, counting()) → Map<Boolean, Long> (counts per partition)
  • partitioningBy(isPassing, summingInt(Student::getScore)) → Map<Boolean, Integer> (sum of scores per partition)
  • partitioningBy(isActive, toSet()) → Map<Boolean, Set<T>> (sets instead of lists)

Key Takeaway: Use partitioningBy(predicate, downstream) to transform each partition with a downstream collector—counting, summing, or collecting differently—rather than keeping the default lists.