Course contentsShow
← Java
Lesson 1538 of 2,87033. Streams API: Terminal OperationsFree lesson

Match Operations on Empty Streams

Understand the behavior of match operations on empty streams: anyMatch returns false, allMatch and noneMatch return true.

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:

  • anyMatch returns false: Makes sense—if there are no elements, there's nothing that could match.
  • allMatch returns true: Surprising! But logically sound—there are no elements that violate the condition.
  • noneMatch returns true: 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.