Course contentsShow
← Java
Lesson 1646 of 2,87035. Functional InterfacesFree lesson

Short-Circuit Evaluation in Predicate Chains

Understand how and() and or() use short-circuit logic, and order predicates for performance optimization.

Short-Circuit Evaluation in Predicate Chains

You'll learn: How and() and or() methods optimize predicate chains by stopping evaluation early, and how to order predicates for maximum performance.

When you chain predicates using and() and or(), Java doesn't always evaluate every predicate—it uses short-circuit logic to skip unnecessary checks once the final result is determined.

How Short-Circuit Logic Works

With and(): If the first predicate returns false, Java skips the rest. Why check more conditions when one failure means the whole chain fails?

With or(): If the first predicate returns true, Java skips the rest. One success means the entire chain succeeds.

Think of it like checking into a members-only event: with and() logic (must have ticket AND be on guest list AND pass age check), the bouncer stops checking the moment you fail any requirement. With or() logic (VIP OR staff OR press pass), they let you in the moment any credential succeeds.

Ordering Predicates for Performance

This behavior means order matters for performance:

Predicate<String> isExpensive = s -> expensiveDatabaseCheck(s);
Predicate<String> isCheap = s -> s.length() > 5;

// Inefficient: expensive check runs first
stream.filter(isExpensive.and(isCheap))

// Efficient: cheap check often eliminates need for expensive one
stream.filter(isCheap.and(isExpensive))

Best practice: Place predicates that are fast to evaluate OR likely to fail (for and()) or succeed (for or()) at the front of the chain. This maximizes the chance of short-circuiting before reaching costly operations.

Key Takeaway: and() and or() use short-circuit evaluation—order your predicates with cheap or decisive checks first to avoid unnecessary work and optimize performance.