Codectionary / Developer documentation / Java

Combining Predicates

Build reusable true-or-false rules with Predicate, and, or and negate.

What it is and why to use it

A Predicate<T> is a function-like object that tests a T and returns boolean. Small predicates can name individual conditions and then combine them. This keeps a reusable validation or filtering rule readable without repeating the same expression throughout an application.

How it works

test invokes the rule. and requires both rules, or requires at least one, and negate reverses a result. and and or short-circuit like && and ||: the second test runs only when needed. Here a null guard safely runs before isBlank.

Common mistakes and limitations

Reversing the null guard and content test would call isBlank on null. Do not use predicates with hidden side effects when short-circuiting could skip necessary work.

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

Predicate<String> valid = nonNull.and(nonBlank);

Examples

Combining Predicates

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

import java.util.function.Predicate;

public class Main {
  public static void main(String[] args) {
    Predicate<String> nonNull = value -> value != null;
    Predicate<String> nonBlank = value -> !value.isBlank();
    Predicate<String> valid = nonNull.and(nonBlank);
    System.out.println(valid.test("John"));
    System.out.println(valid.test(null));
    System.out.println(valid.negate().test(" "));
  }
}
  1. nonNull checks reference presence and nonBlank checks text content.
  2. valid.test(null) returns false before nonBlank runs, avoiding a NullPointerException.
  3. A space-only string fails valid, so negate returns true. The same predicate could be passed to stream.filter when cleaning a list of names.
  4. Expected output: true false true

Best practices

  • Name conditions by what they mean.
  • Keep tests deterministic and free of side effects.

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