Course contentsShow
← Java
Lesson 1413 of 2,87031. Streams API: Creation and BasicsFree lesson

Terminal Short-Circuiting: anyMatch, allMatch, noneMatch

How matching operations short-circuit when the result is determinable without checking remaining elements.

Terminal Short-Circuiting: anyMatch, allMatch, noneMatch

You'll learn how matching operations can stop early as soon as they know the final answer.

How Matching Operations Short-Circuit

The three matching operations—anyMatch(), allMatch(), and noneMatch()—are smart enough to stop processing the stream as soon as the result becomes certain. They don't waste time checking every remaining element when it's unnecessary.

anyMatch: Stops at First True

anyMatch(predicate) returns true if any element matches. Once it finds a single match, it immediately returns true without checking the rest:

boolean hasEven = Stream.of(1, 3, 4, 7, 9)
    .anyMatch(n -> n % 2 == 0);
// Stops at 4, never checks 7 or 9

allMatch: Stops at First False

allMatch(predicate) returns true only if all elements match. The moment it finds one that doesn't match, it returns false:

boolean allPositive = Stream.of(2, 4, -1, 6, 8)
    .allMatch(n -> n > 0);
// Stops at -1, never checks 6 or 8

noneMatch: Stops at First True

noneMatch(predicate) returns true if no elements match. If it finds any match, it immediately returns false:

boolean noNegatives = Stream.of(1, 3, -5, 7)
    .noneMatch(n -> n < 0);
// Stops at -5, never checks 7

The Analogy

Think of checking if everyone in a movie theater has a ticket. For anyMatch, you stop when you find one person without a ticket. For allMatch, you stop when you find someone with a ticket. You don't need to check every single person once the answer is determined.

Key Takeaway: The matching operations (anyMatch, allMatch, noneMatch) short-circuit by stopping stream processing as soon as the result is certain, making them efficient especially with large or infinite streams.