CodeBlanks Logo Icon CodeBlanks

partitioningBy

Learn two-way partitioning with Collectors.partitioningBy.

Splitting in two: partitioningBy

Collectors.partitioningBy splits elements into two groups based on a single condition. The condition is a Predicate<T> and the result is always Map<Boolean, List<T>>: the true key holds elements that match, the false key those that do not.

Example: numbers.stream().collect(Collectors.partitioningBy(n -> n % 2 == 0)). Even numbers land in the true group, odd ones in false. Unlike groupingBy, this collector always produces exactly two groups.

partitioningBy with a downstream collector

The two-argument overload applies a downstream collector to each partition. This is handy not only for keeping lists but for counting or averaging each side.

Example: Collectors.partitioningBy(n -> n % 2 == 0, Collectors.counting()). This call returns Map<Boolean, Long>: true is the number of even values, false the number of odd ones. You get a summary of each partition in a single line, with no extra pass needed.

Practice Partition numbers by even/odd

Create a list of the numbers 1, 2, 3, 4, 5. Partition the stream with Collectors.partitioningBy(n -> n % 2 == 0). Then print the counts of the false and true keys on separate lines using System.out.println; print false: first, then true: .

Starter code

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

// Partition numbers into even/odd
// Use Collectors.partitioningBy
// Print the count of each side

Sample solution

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

public class PartitionNumbers {
    public static void main(String[] args) {
        List<Integer> numbers = List.of(1, 2, 3, 4, 5);
        Map<Boolean, List<Integer>> parts = numbers.stream()
            .collect(Collectors.partitioningBy(n -> n % 2 == 0));
        System.out.println("false: " + parts.get(false).size());
        System.out.println("true: " + parts.get(true).size());
    }
}

Expected output

false: 3
true: 2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the partitioningBy concepts

Term Meaning
partitioningBy Splits in two
Predicate<T> Condition function
true key Matching elements
false key Non-matching elements

2 What type does partitioningBy(n -> n % 2 == 0) return?

  • List<Integer>
  • Map<Boolean, Long>
  • Map<Boolean, List<Integer>> Correct answer
  • Optional<Integer>

Explanation: The single-argument partitioningBy returns Map<Boolean, List<T>>.

3 Complete the partitioningBy call

Question
Map<Boolean, List<Integer>> parts = numbers.stream()
    .collect(Collectors.partitioningBy(____));
Answer
Map<Boolean, List<Integer>> parts = numbers.stream()
    .collect(Collectors.partitioningBy(n -> n % 2 == 0));

Explanation: This condition puts even numbers in the true partition.

All lessons in Advanced