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

partitioningBy vs groupingBy: Choosing the Right Tool

Compare performance and semantics: partitioningBy guarantees two keys and is optimized for binary splits, while groupingBy handles arbitrary keys.

partitioningBy vs groupingBy: Choosing the Right Tool

What you'll learn: You'll discover when to use partitioningBy instead of groupingBy based on performance and semantic guarantees.

The Fundamental Difference

Both collectors classify stream elements into groups, but they serve different purposes. partitioningBy is specialized for binary (true/false) splits, while groupingBy handles arbitrary classifications with any number of keys.

Think of it like sorting mail: partitioningBy is like separating letters into "local" and "out-of-state" (always two piles, even if one is empty). groupingBy is like sorting by zip code—you don't know how many piles you'll have until you're done.

Performance Considerations

partitioningBy is optimized for binary decisions. It:

  • Always returns exactly two keys (true and false)
  • Guarantees both partitions exist in the result map, even if empty
  • Can be slightly faster due to this specialized behavior

groupingBy, by contrast:

  • Creates keys dynamically based on the classifier function
  • May return anywhere from zero to many keys
  • Only includes keys that actually appeared in the stream

Semantic Guarantees

With partitioningBy, you always get a complete picture—both sides of the split. This matters when you need to reference both categories explicitly:

Map<Boolean, List<Employee>> byStatus = 
    employees.stream()
             .collect(partitioningBy(Employee::isActive));
// Guaranteed: byStatus.get(true) and byStatus.get(false) both exist

With groupingBy, missing keys mean no elements matched that classification—you must check for null or use getOrDefault().

When to Choose Which

Use partitioningBy when your logic is binary: active/inactive, valid/invalid, passed/failed.

Use groupingBy when you have multiple categories: departments, age ranges, status codes.

Key Takeaway: Choose partitioningBy for binary splits to get guaranteed two-key maps and optimized performance; use groupingBy for flexible, multi-category classification where the number of groups is unknown or variable.