Collectors Partitioning And Grouping

Split a stream into two buckets with partitioningBy and roll up grouped statistics with groupingBy plus downstream counting and averaging collectors.

JavaData Integrity

Code

snippet
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class PartitionRollup {

    record Order(String region, int amount, boolean rush) {}

    public static void main(String[] args) {
        List<Order> orders = List.of(
                new Order("eu", 120, true),
                new Order("eu", 80, false),
                new Order("na", 95, false),
                new Order("na", 210, true),
                new Order("apac", 45, false));

        // partitioningBy 恒产生 true/false 两个桶(即使为空)
        Map<Boolean, List<Order>> byRush =
                orders.stream().collect(Collectors.partitioningBy(Order::rush));
        System.out.println("rush count     = " + byRush.get(true).size());
        System.out.println("standard count = " + byRush.get(false).size());

        // groupingBy + downstream:每区域订单数与平均金额
        Map<String, Long> countByRegion =
                orders.stream().collect(Collectors.groupingBy(Order::region, Collectors.counting()));
        Map<String, Double> avgByRegion =
                orders.stream().collect(Collectors.groupingBy(Order::region,
                        Collectors.averagingInt(Order::amount)));

        countByRegion.forEach((region, count) ->
                System.out.printf("%s: %d orders, avg %.1f%n", region, count, avgByRegion.get(region)));
    }
}

How the snippet works

Collectors Partitioning And Grouping keeps everything in the classes PartitionRollup and Order and the function main.

The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable.

Applying it

Running the file prints labeled results such as rush count =, standard count = — each operation’s effect is visible in the output.

Statements that matter

orders.stream().collect(Collectors.groupingBy(Order::region, Collectors.counting()));
orders.stream().collect(Collectors.partitioningBy(Order::rush));
orders.stream().collect(Collectors.groupingBy(Order::region,
Collectors.averagingInt(Order::amount)));

Interactive Tools for This Topic

FAQ

What does Collectors Partitioning And Grouping print when run?
Invoke the file as-is — the `rush count =`, `standard count =` prefixes identify which step printed each line.