Streams: partitioningBy always returns both keys

partitioningBy gives a map with false and true present even when one side is empty, unlike groupingBy on a boolean expression.

Code
var nums = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

Map<Boolean, List<Integer>> parts = nums.stream()
        .collect(Collectors.partitioningBy(n -> n % 2 == 0));
System.out.println("odd  = " + parts.get(false));
System.out.println("even = " + parts.get(true));

Map<Boolean, Long> counts = nums.stream()
        .collect(Collectors.partitioningBy(n -> n > 100, Collectors.counting()));
System.out.println("both keys present even when empty: " + counts);
Output
odd  = [1, 3, 5, 7, 9]
even = [2, 4, 6, 8, 10]
both keys present even when empty: {false=10, true=0}
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-30