CKTIS / Java
Predicate.test() — evaluating a condition
Use `test(T t)` to check a condition against one input. It returns the primitive `boolean` value `true` if the input meets the condition, or `false` if it does not.
Version: Java SE 21
Syntax
boolean test(T t);
// Invocation: predicate.test(value)java.util.function.Predicate<T> is a functional interface that represents a condition on one value. T is the input type: with a Predicate<String>, the input is a String.
Predicate.test() is shorthand for the instance method boolean test(T t). The call predicate.test(value) requires one argument. It evaluates the condition for that value and returns true if the condition is met or false if it is not. You can use the result directly in an if statement.
Assigning a lambda to a Predicate<T> variable defines the condition without checking it yet. Each call to test runs the lambda with the supplied argument. How null is handled depends on the predicate implementation: in this example, test(null) would throw a NullPointerException at text.length() instead of returning false.
Examples
import java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
Predicate<String> hasAtLeastThreeChars = text -> text.length() >= 3;
System.out.println(hasAtLeastThreeChars.test("cat"));
System.out.println(hasAtLeastThreeChars.test("hi"));
}
}
Result
true false
The condition `text.length() >= 3` includes a length of exactly 3, so the program prints `true` for `"cat"`. It prints `false` for `"hi"`, which has length 2.
Related lessons
- Java · Lesson 62 · Basic · Version: 2