Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Predicate — composing boolean conditions

Predicate<T> describes a condition on one argument of type T. It supports testing values and combining conditions using logical AND, OR, and negation.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

boolean test(T t)
default Predicate<T> and(Predicate<? super T> other)
default Predicate<T> negate()
default Predicate<T> or(Predicate<? super T> other)
static <T> Predicate<T> not(Predicate<? super T> target)

java.util.function.Predicate<T> is a functional interface: it accepts one argument of type T and returns boolean. Implement it with a lambda or method reference. Predicate.test (test(t)) checks the argument.

Predicate.and (p.and(q)) and Predicate.or (p.or(q)) create new predicates. They short-circuit: and skips q when p returns false; or skips q when p returns true.

Predicate.negate (p.negate()) reverses the result. Static Predicate.not(p), available since Java 11, returns the result of p.negate(). Composition does not yet test an argument — test does that.

A predicate's input may be null only if its implementation handles it. In the example, present.and(longEnough) guards the length() call. Passing null as the predicate to and, or, or not throws NullPointerException. Exceptions during and and or evaluation propagate to the caller; an exception from the first predicate prevents evaluation of the second.

Examples

import java.util.function.Predicate;

public class Main {
    public static void main(String[] args) {
        Predicate<String> present = s -> s != null;
        Predicate<String> longEnough = s -> s.length() >= 3;
        Predicate<String> valid = present.and(longEnough);
        Predicate<String> accepted = valid.or(s -> "OK".equals(s));

        System.out.println(valid.test(null));
        System.out.println(accepted.test("OK"));
        System.out.println(valid.negate().test("hi"));
        System.out.println(Predicate.not(valid).test("Java"));
    }
}

Result

false
true
true
false

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources