Java

Collectors.partitioningBy — Split by Predicate

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Special case of groupingBy when the key is boolean — returns a `Map<Boolean, List<T>>` for the "true" and "false" buckets. Slightly more efficient than groupingBy.
Java
Raw
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;

class Demo {
    void example() {
        var nums = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        Map<Boolean, List<Integer>> split = nums.stream()
            .collect(partitioningBy(n -> n % 2 == 0));
        System.out.println(split.get(true));    // [2, 4, 6, 8, 10]
        System.out.println(split.get(false));   // [1, 3, 5, 7, 9]

        // With downstream — count instead of collect
        Map<Boolean, Long> counts = nums.stream()
            .collect(partitioningBy(n -> n > 5, counting()));
        System.out.println(counts);              // {false=5, true=5}
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.