00:00

Java Stream anyMatch(), allMatch() and noneMatch()

Last updated:

The match operations anyMatch(), allMatch() and noneMatch() are short-circuiting terminal operations of java.util.stream.Stream, available since Java 8. Each takes a Predicate and returns a boolean: whether at least one, every, or no element matches.

They are the stream way to answer yes-or-no questions such as "is any order overdue?" or "are all fields valid?". This tutorial covers all three, their surprising but logical results on empty streams, and how early they stop.

1. Syntax and Method Signatures

Stream.java (API)
// java.util.stream.Stream<T> (Java 8)
boolean anyMatch(Predicate<? super T> predicate)    // true if at least one element matches
boolean allMatch(Predicate<? super T> predicate)    // true if every element matches
boolean noneMatch(Predicate<? super T> predicate)   // true if no element matches

// primitive versions take IntPredicate, LongPredicate, DoublePredicate
Usage
boolean hasOverdue = invoices.stream().anyMatch(Invoice::isOverdue);

2. How the Match Operations Work

Each operation tests elements until the answer is decided. anyMatch() stops at the first match and returns true. allMatch() stops at the first element that does not match and returns false. noneMatch() stops at the first match and returns false. If no element decides the answer, the whole stream is read.

On an empty stream, anyMatch() returns false (there is no matching element), while allMatch() and noneMatch() return true (there is no element that breaks the rule). This is called vacuous truth, and it matches the rules of logic.

When each match operation stops For the stream 4, 9, 15, 6 and the predicate greater than 8: anyMatch stops at 9 and returns true. allMatch stops at 4, the first non-match, and returns false. noneMatch stops at 9, the first match, and returns false. On an empty stream anyMatch returns false while allMatch and noneMatch return true. STOPS AT RESULT EMPTY STREAM anyMatch(n > 8) 9: first match true false allMatch(n > 8) 4: first miss false true noneMatch(n > 8) 9: first match false true
Figure 1: Input: 4, 9, 15, 6. Each operation stops as soon as the answer is certain. On an empty stream, "all" and "none" are vacuously true.

3. Java Examples

Example 1: The three questions on one data set (Java 9+)

Check a batch of product prices: is any above 10,000, are all positive, and is none zero?

PriceChecks.java
import java.util.List;

public class PriceChecks {

    public static void main(String[] args) {
        List<Integer> prices = List.of(499, 12_999, 1_250, 89);

        System.out.println("Any above 10000? " + prices.stream().anyMatch(p -> p > 10_000));
        System.out.println("All positive?    " + prices.stream().allMatch(p -> p > 0));
        System.out.println("None zero?       " + prices.stream().noneMatch(p -> p == 0));
    }
}
Output
Any above 10000? true
All positive?    true
None zero?       true

How it works: Each method answers one question with a boolean. noneMatch(p) is the same as !anyMatch(p), but reads more naturally.

Example 2: Validating a form (Java 11+)

A registration form is valid only if every required field is filled in.

FormValidation.java
import java.util.LinkedHashMap;
import java.util.Map;

public class FormValidation {

    public static void main(String[] args) {
        Map<String, String> form = new LinkedHashMap<>();
        form.put("name", "Tanvi");
        form.put("email", "tanvi@mail.in");
        form.put("phone", "  ");

        boolean complete = form.values().stream().allMatch(v -> v != null && !v.isBlank());
        String firstMissing = form.entrySet().stream()
                .filter(e -> e.getValue() == null || e.getValue().isBlank())
                .map(Map.Entry::getKey)
                .findFirst()
                .orElse("none");

        System.out.println("Form complete? " + complete);
        System.out.println("First missing field: " + firstMissing);
    }
}
Output
Form complete? false
First missing field: phone

How it works: allMatch() answers the yes-or-no question. When the answer is no, a separate filter().findFirst() finds which field caused it.

Example 3: Short-circuiting saves work

Check whether any transaction in a large batch is suspicious, counting how many were inspected.

EarlyExit.java
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

public class EarlyExit {

    public static void main(String[] args) {
        AtomicInteger inspected = new AtomicInteger();

        boolean suspicious = IntStream.rangeClosed(1, 1_000_000)
                .map(id -> {
                    inspected.incrementAndGet();
                    return id * 37 % 1000;          // stands in for a risk score
                })
                .anyMatch(score -> score > 990);

        System.out.println("Suspicious transaction found: " + suspicious);
        System.out.println("Transactions inspected: " + inspected.get());
    }
}
Output
Suspicious transaction found: true
Transactions inspected: 27

How it works: anyMatch() stopped after 27 of a million elements, because transaction 27 scored 999. With filter().count() > 0 all million would be processed.

Example 4: Empty streams and vacuous truth (Java 9+)

Show what each match operation returns when a customer has no orders.

EmptyMatches.java
import java.util.List;

public class EmptyMatches {

    public static void main(String[] args) {
        List<Integer> noOrders = List.of();

        System.out.println("anyMatch:  " + noOrders.stream().anyMatch(o -> o > 0));
        System.out.println("allMatch:  " + noOrders.stream().allMatch(o -> o > 0));
        System.out.println("noneMatch: " + noOrders.stream().noneMatch(o -> o > 0));

        boolean allPaidAndHasOrders = !noOrders.isEmpty() && noOrders.stream().allMatch(o -> o > 0);
        System.out.println("Has orders and all paid: " + allPaidAndHasOrders);
    }
}
Output
anyMatch:  false
allMatch:  true
noneMatch: true
Has orders and all paid: false

How it works: allMatch() returns true for an empty stream. If your rule means "there are orders and all are paid", check for emptiness separately, as the last line does.

4. Real-World Use Cases

  • Validation: all line items have positive quantities; no field is blank.
  • Authorisation: does the user have any of the required roles?
  • Alerts: is any server unhealthy, any payment failed, any stock level critical?
  • Business rules: none of the items in the cart is restricted for the user's region.

5. Important Points

  • Empty streams: anyMatch is false; allMatch and noneMatch are true.
  • Short-circuiting: they stop as soon as the answer is known and can work on infinite streams when the answer is decided.
  • Deterministic in parallel: the result does not depend on order, so parallel runs give the same answer.
  • Nulls: the predicate must handle null elements if they can occur.
  • Single use: each call consumes the stream; create a new one for each question.

6. Match Operations Compared

MethodReturns true whenStops early onEmpty stream
anyMatch(p)At least one element matchesFirst matchfalse
allMatch(p)Every element matchesFirst non-matchtrue
noneMatch(p)No element matchesFirst matchtrue
filter(p).count() > 0Same as anyMatchNeverfalse
findFirst()Returns the element itselfFirst elementEmpty Optional

7. Common Mistakes and Best Practices

Forgetting the empty case with allMatch()

allMatch() on an empty stream is true, which can approve an empty order or an empty upload. Check isEmpty() first when emptiness is invalid, as in Example 4.

Negating in the wrong place

Wrong
boolean noneExpired = !items.stream().allMatch(Item::isExpired);   // means "not all expired", not "none expired"
Right
boolean noneExpired = items.stream().noneMatch(Item::isExpired);

Other mistakes to avoid

  • Counting to test existence. Use anyMatch().
  • Putting side effects in the predicate. It may not run for every element.
  • Reusing one stream for several checks. Each check needs its own stream.

8. Summary

  • anyMatch(), allMatch() and noneMatch() return a boolean for a Predicate.
  • They short-circuit as soon as the answer is known.
  • On empty streams, "all" and "none" are true and "any" is false.
  • Prefer them over count() for existence checks.

9. References