How do I use Collectors.partitioningBy() method?

Collectors.partitioningBy() is a special case of a grouping collector in Java’s Stream API. It partitions or divides the input elements into two groups, based on the result of a Predicate function. One group for which the Predicate function returns true, and the other where it returns false.

Each group is a List of elements, and the method returns a Map where the keys are Boolean values (true and false), and the values are the resulting groups.

Here’s a simple example:


import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class OddEvenNumberPartitioning {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        Map<Boolean, List<Integer>> isEven =
                .collect(Collectors.partitioningBy(num -> num % 2 == 0));

        System.out.println("Partition of Even Numbers: " + isEven.get(true));
        System.out.println("Partition of Odd Numbers: " + isEven.get(false));


Partition of Even Numbers: [2, 4, 6, 8, 10]
Partition of Odd Numbers: [1, 3, 5, 7, 9]

In this example, we’re partitioning a list of integers into even and odd numbers. The Predicate function num -> num % 2 == 0 returns true for even numbers and false for odd numbers.

The value that partitioningBy() method returns is a Map where the key true maps to a list of numbers for which the Predicate was true (even numbers), and the key false maps to a list of numbers for which the Predicate was false (odd numbers).

You can use partitioningBy() to easily categorize elements of a stream where the categorization criterion can be represented with a boolean value (i.e., you have a binary condition to divide your elements).