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

Aggregating Values in Partitions

Combine partitioningBy with summingInt, averagingDouble, or other numeric collectors to compute statistics for each partition.

Aggregating Values in Partitions

You'll learn how to calculate numeric statistics like sums, averages, and totals within each partition created by partitioningBy.

Core Idea

In the previous lesson, you learned to count elements in each partition. But what if you need richer statistics—like the total price of expensive versus inexpensive items, or the average age of adults versus minors? By combining partitioningBy with numeric collectors (summingInt, averagingDouble, etc.), you can compute these aggregations for each side of your boolean split.

Think of it like sorting your shopping cart into "perishable" and "non-perishable" items, then calculating the total cost for each category separately. The partition separates the items; the downstream collector does the math.

How It Works

Instead of using Collectors.counting() as your downstream collector, use:

  • summingInt(mapper) to sum integer values
  • averagingDouble(mapper) to calculate average values
  • summarizingInt(mapper) for complete statistics (count, sum, min, average, max)

The result is still a Map<Boolean, R> where R is the aggregated result type (e.g., Integer for sums, Double for averages).

Map<Boolean, Integer> totalPrices = products.stream()
    .collect(partitioningBy(
        p -> p.getPrice() > 100,
        summingInt(Product::getPrice)
    ));
// {false=450, true=780} — total for cheap vs expensive
Map<Boolean, Double> avgAges = people.stream()
    .collect(partitioningBy(
        p -> p.getAge() >= 18,
        averagingDouble(Person::getAge)
    ));
// {false=12.5, true=42.3} — average age for minors vs adults

Key Takeaway:
Use partitioningBy with numeric collectors like summingInt or averagingDouble to compute statistics separately for each partition, giving you targeted insights into both sides of your boolean classification.