Short-Circuiting Behavior of allMatch
What you'll learn: How allMatch avoids wasting time by stopping immediately when it finds a non-matching element.
The Core Idea
While allMatch checks whether every element in a stream satisfies a condition, it doesn't need to examine every element to know the answer is "no." As soon as it encounters the first element that doesn't match the predicate, allMatch returns false and stops processing—no matter how many elements remain unprocessed.
Think of it like checking if every student passed an exam. If you're reviewing papers one by one and find a single failing grade, you already know the answer is "not everyone passed." There's no reason to check the remaining papers.
How It Works
When you call allMatch(predicate):
- The stream starts evaluating elements one by one
- Each element is tested against the predicate
- If an element returns
false,allMatchimmediately returnsfalseand terminates - Only if all elements return
truedoesallMatchreturntrue
This makes allMatch highly efficient when dealing with large streams where failures might occur early.
Performance Impact
List<Integer> numbers = Arrays.asList(2, 4, 7, 8, 10, 12, 14, 16);
boolean allEven = numbers.stream()
.allMatch(n -> n % 2 == 0); // Stops at 7 (3rd element)
In this example, the stream doesn't check elements 8, 10, 12, 14, or 16. Once it hits 7 (which is odd), allMatch returns false immediately.
Key Takeaway: allMatch short-circuits on the first false result, making it efficient for validation checks where early failures are common—you only pay for processing until the first mismatch is found.