Codectionary / Developer documentation / Java

Splitting Results with partitioningBy

Divide a stream into true and false groups using one condition.

What it is and why to use it

partitioningBy is a specialised collector for two-way decisions. It places matching elements under true and all others under false. A pass/fail list or valid/invalid split can use the same condition once while retaining both sides for later processing.

How it works

The predicate score -> score >= 50 determines the bucket. Unlike a general grouping operation, the resulting map contains both boolean keys even when one partition is empty. The example retrieves each list explicitly instead of depending on map iteration order.

Common mistakes and limitations

A partition key is boolean, not the text "true" or "false". Use groupingBy when you need more than two categories. Avoid predicates whose result changes during traversal.

Try it and keep learning

Save the complete example below as Main.java. With a JDK supporting Java 17, compile using javac --release 17 Main.java, then run java Main from the same directory. These examples need only the standard library and fixed input; they do not require packages, files or network access.

Syntax

collect(Collectors.partitioningBy(score -> score >= 50))

Examples

Splitting Results with partitioningBy

Complete Main.java example — Java 17 or later, without preview features.

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

public class Main {
  public static void main(String[] args) {
    Map<Boolean, List<Integer>> groups = List.of(40, 72, 90).stream()
        .collect(Collectors.partitioningBy(score -> score >= 50));
    System.out.println(groups.get(true));
    System.out.println(groups.get(false));
  }
}
  1. 72 and 90 meet the threshold and enter the true partition.
  2. 40 does not meet it and enters the false partition.
  3. Retrieving both partitions keeps unsuccessful items available for feedback rather than discarding them with filter. The source list is unchanged.
  4. Expected output: [72, 90] [40]

Best practices

  • Name the condition clearly.
  • Use an additional collector such as counting when lists are unnecessary.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading