allMatch() is a short-circuiting terminal Stream operation that returns true only if every element in the stream satisfies the given predicate.
Key Points: • allMatch(predicate) stops as soon as it finds one element that fails the predicate, returning false immediately. • It returns true for an empty stream, since there's no element to violate the condition - this is called a vacuous truth. • It's one of three related short-circuiting match operations, alongside anyMatch() and noneMatch(). • Because it's short-circuiting, allMatch() can be far more efficient than mapping every element and checking a full collection. • Commonly used for validation, such as confirming every value in a batch passes a business rule before processing continues.
Example: Given the list [2, 4, 6, 8], calling allMatch(n -> n > 0) returns true since every element is positive.
Code Example:
boolean allPositive = numbers.stream()
.allMatch(n -> n > 0);Interview Tip: A concise interview answer is:
"allMatch(predicate) returns true only if every element satisfies the condition, and it short-circuits as soon as it finds one that doesn't, which makes it efficient for validating that an entire collection meets a rule before continuing."