CKTIS / Java
Predicate.or(): logical OR for predicates
Combine two predicates into one reusable condition. The second predicate is evaluated only when the first returns `false`.
Version: Java SE 21
Syntax
default Predicate<T> or(Predicate<? super T> other)
Predicate<T> combined = first.or(other);
boolean matches = combined.test(value);Predicate.or() is a default method on java.util.function.Predicate<T>. The call first.or(other) takes one argument and returns a Predicate<T> without testing any input. The parameter Predicate<? super T> accepts a predicate for T or a supertype of T, such as a Predicate<Object> when first is a Predicate<String>.
Calling combined.test(value) runs first first. If it returns true, the result is true and other is skipped. If it returns false, other tests the same value and supplies the result. The result is false only when both predicates return false. The expression first.test(value) || other.test(value) follows the same short-circuit rule but produces a boolean, not a reusable predicate.
Calling first.or(null) throws NullPointerException immediately, even if first always returns true. That is different from passing null to test: in that case, behavior depends on the predicates that actually run. An exception from either evaluated predicate propagates to the caller; if first throws, other is not evaluated.
Examples
import java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
Predicate<String> startsWithA = name -> name.startsWith("A");
Predicate<String> atLeastFive = name -> {
System.out.println("length check: " + name);
return name.length() >= 5;
};
Predicate<String> matches = startsWithA.or(atLeastFive);
for (String name : new String[] {"Amy", "Bruno", "Bo"}) {
System.out.println(name + ": " + matches.test(name));
}
}
}Result
Amy: true length check: Bruno Bruno: true length check: Bo Bo: false
`Amy` matches the first condition, so `length check: Amy` is not printed. The length check runs for `Bruno` and `Bo`: `Bruno` matches because it has at least five characters, but `Bo` does not.
Related lessons
- Java · Lesson 62 · Basic · Version: 2