Match Operations on Empty Streams
What You'll Learn
You'll learn the specific, consistent behavior of anyMatch, allMatch, and noneMatch when applied to streams that contain no elements.
The Empty Stream Edge Case
When a stream has no elements, the match operations behave in ways that follow logical consistency—but might surprise you at first:
anyMatchreturnsfalse: Makes sense—if there are no elements, there's nothing that could match.allMatchreturnstrue: Surprising! But logically sound—there are no elements that violate the condition.noneMatchreturnstrue: Also makes sense—there are no elements that match.
Why allMatch Returns True
Think of allMatch as asking: "Are there any elements that don't match?" For an empty stream, the answer is "no"—there are no counterexamples to disprove your condition. This is called a vacuous truth in logic: a statement about an empty set is considered true because it cannot be falsified.
Example Without Code
Imagine checking students' test scores:
anyMatch(score > 90)on an empty classroom →false(no one scored above 90)allMatch(score > 90)on an empty classroom →true(no one scored below 90 either!)noneMatch(score > 90)on an empty classroom →true(correct, no one scored above 90)
Practical Impact
This behavior matters when filtering streams that might become empty. Always consider: if your upstream filters produce zero elements, will allMatch returning true cause logic errors in your application?
Key Takeaway: On empty streams, anyMatch returns false, while both allMatch and noneMatch return true—a consequence of vacuous truth in logical operations.