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

allMatch: Testing If All Elements Match

Use allMatch to verify that every element in the stream satisfies the predicate, returning false at the first mismatch.

allMatch: Testing If All Elements Match

What you'll learn: How to use allMatch to verify that every single element in a stream satisfies a given condition, stopping immediately if any element fails.


What allMatch Does

The allMatch method is a terminal operation that checks whether all elements in a stream meet a specified condition. It takes a Predicate and returns true only if every element satisfies that predicate. If it encounters even one element that doesn't match, it immediately returns false without checking the rest.

Think of it like a quality inspector: If you're checking a batch of products and need every single one to pass inspection, you can stop the moment you find one defect. There's no point continuing — the batch has already failed.

Basic Usage

List<Integer> numbers = List.of(2, 4, 6, 8, 10);
boolean allEven = numbers.stream()
                         .allMatch(n -> n % 2 == 0);
System.out.println(allEven);  // true

List<Integer> mixed = List.of(2, 4, 5, 8);
boolean stillAllEven = mixed.stream()
                            .allMatch(n -> n % 2 == 0);
System.out.println(stillAllEven);  // false (stops at 5)

Short-Circuiting Behavior

Like anyMatch, allMatch is a short-circuiting operation. The moment it finds an element that doesn't satisfy the predicate, it stops processing immediately and returns false. This makes it efficient even on large or infinite streams.

Stream.of("apple", "apricot", "avocado", "banana")
      .allMatch(s -> s.startsWith("a"));  // false, stops at "banana"

Empty Streams

A subtle but important detail: allMatch returns true for an empty stream. Logically, if there are no elements to fail the test, then "all elements" (none) satisfy the condition.

Key Takeaway: Use allMatch to verify every element meets a condition — it returns false immediately upon the first mismatch, making it both powerful and efficient for validation tasks.