Skip to lesson

anyMatch, allMatch and noneMatch

anyMatch, allMatch and noneMatch are terminal operations that answer a yes or no question about a stream. Each takes a Predicate and returns a plain boolean: is there at least one, are all of them, or are none of them?

Three yes or no checks

Many checks in real apps are yes or no. Did any student fail? Did every payment succeed? Is there no negative amount in the bill? Before streams, each one was a loop with a boolean flag and a break.

Example 1 · anyMatch, allMatch and noneMatch on marks

MatchDemo.javaJava
import java.util.List;
public class MatchDemo {    public static void main(String[] args) {        List<Integer> marks = List.of(72, 38, 91, 64, 29);
        // old way: a flag and a break        boolean anyFailLoop = false;        for (int m : marks) {            if (m < 35) {                anyFailLoop = true;                break;            }        }        System.out.println("Loop, any fail: " + anyFailLoop);
        boolean anyFail = marks.stream().anyMatch(m -> m < 35);        boolean allPass = marks.stream().allMatch(m -> m >= 35);        boolean noneAbove100 = marks.stream().noneMatch(m -> m > 100);
        System.out.println("Any fail: " + anyFail);        System.out.println("All pass: " + allPass);        System.out.println("No mark above 100: " + noneAbove100);        System.out.println("Any distinction: " + marks.stream().anyMatch(m -> m >= 90));    }}
Output
Loop, any fail: true
Any fail: true
All pass: false
No mark above 100: true
Any distinction: true

What this code does

  • Each method takes a Predicate<Integer> and returns a boolean. The one line anyMatch(m -> m < 35) replaces the flag, the loop, the if and the break.
  • 29 is below 35, so anyMatch is true and allMatch is false. No mark is above 100, so noneMatch(m -> m > 100) is true: a quick check that the data is valid.

Streams give one method for each question. Each takes a Predicate<T>, a lambda that returns true or false for one element.

  • anyMatch(p): true if at least one element passes p.
  • allMatch(p): true if every element passes p.
  • noneMatch(p): true if no element passes p.
  • noneMatch(p) is the same as !anyMatch(p); pick the one that reads like the question.

Short-circuiting: they stop early

A short-circuiting operation stops as soon as the answer is known, like && and || in an if. anyMatch stops at the first element that passes: one is enough for "yes". allMatch stops at the first element that fails: one is enough for "no".

anyMatch(m -> m >= 70) over the marks 45, 62, 78, 90 and 55. 45 fails, 62 fails, 78 passes, so the stream stops and returns true. The marks 90 and 55 are never looked at.

Example 2 · Short-circuiting traced step by step

ShortCircuitDemo.javaJava
import java.util.List;
public class ShortCircuitDemo {    public static void main(String[] args) {        List<Integer> marks = List.of(72, 38, 91, 64, 29);
        System.out.println("anyMatch(m >= 90):");        boolean any = marks.stream()                           .peek(m -> System.out.println("  checking " + m))                           .anyMatch(m -> m >= 90);        System.out.println("  result " + any);
        System.out.println("allMatch(m >= 40):");        boolean all = marks.stream()                           .peek(m -> System.out.println("  checking " + m))                           .allMatch(m -> m >= 40);        System.out.println("  result " + all);
        System.out.println("noneMatch(m < 20):");        boolean none = marks.stream()                            .peek(m -> System.out.println("  checking " + m))                            .noneMatch(m -> m < 20);        System.out.println("  result " + none);    }}
Output
anyMatch(m >= 90):
  checking 72
  checking 38
  checking 91
  result true
allMatch(m >= 40):
  checking 72
  checking 38
  result false
noneMatch(m < 20):
  checking 72
  checking 38
  checking 91
  checking 64
  checking 29
  result true

What this code does

  • anyMatch stops at 91, the first mark that passes, so 64 and 29 are never checked. allMatch stops at 38, the first mark that fails.
  • noneMatch must read every mark to be sure none is below 20. Short-circuiting saves work only when the answer is found early; in the worst case all elements are checked.

noneMatch stops at the first element that passes. Because the stream is lazy, the steps before the check stop too. In orders.stream().map(...).anyMatch(...), map runs only for the elements up to the first match. On a list of a lakh orders where the third one matches, only three elements are ever touched.

So never put a side effect you depend on before a match operation. The elements after the answer are simply never seen.

Real-world use: did every payment succeed

A UPI batch of salary payments must be checked before the report is sent. allMatch(p -> p.status().equals("SUCCESS")) says whether the whole batch went through. anyMatch(p -> p.status().equals("FAILED")) says whether someone must retry.

Example 3 · Did every payment in the batch succeed?

PaymentBatchDemo.javaJava
import java.util.List;
record Payment(String id, String status, int amount) {}
public class PaymentBatchDemo {    public static void main(String[] args) {        List<Payment> batch = List.of(                new Payment("UPI501", "SUCCESS", 25000),                new Payment("UPI502", "SUCCESS", 18000),                new Payment("UPI503", "FAILED", 22000),                new Payment("UPI504", "SUCCESS", 30000));
        boolean allPaid = batch.stream().allMatch(p -> p.status().equals("SUCCESS"));        boolean needsRetry = batch.stream().anyMatch(p -> p.status().equals("FAILED"));        boolean amountsValid = batch.stream().noneMatch(p -> p.amount() <= 0);
        System.out.println("All salaries paid: " + allPaid);        System.out.println("Needs retry: " + needsRetry);        System.out.println("Amounts valid: " + amountsValid);
        if (needsRetry) {            batch.stream()                 .filter(p -> p.status().equals("FAILED"))                 .forEach(p -> System.out.println("Retry " + p.id() + " for Rs. " + p.amount()));        }    }}
Output
All salaries paid: false
Needs retry: true
Amounts valid: true
Retry UPI503 for Rs. 22000

What this code does

  • Each check reads like the business rule: all paid, any failed, no bad amount. The results are plain boolean values, ready for an if.
  • A match operation only answers yes or no. To know which payment failed, use filter with forEach or toList.

noneMatch(p -> p.amount() <= 0) checks that no payment has a zero or negative amount.

These checks read like the business rule itself, so a reviewer can match the code to the requirement line by line.

Trap: allMatch on an empty stream is true

On an empty stream, allMatch returns true, noneMatch returns true and anyMatch returns false, whatever the predicate.

Example 4 · Trap: an empty batch says "all paid"

EmptyMatchDemo.javaJava
import java.util.List;
public class EmptyMatchDemo {    public static void main(String[] args) {        List<String> statuses = List.of();   // the payment file failed to load
        System.out.println("allMatch:  " + statuses.stream().allMatch(s -> s.equals("SUCCESS")));        System.out.println("anyMatch:  " + statuses.stream().anyMatch(s -> s.equals("SUCCESS")));        System.out.println("noneMatch: " + statuses.stream().noneMatch(s -> s.equals("FAILED")));
        // even an impossible condition is "true for all" of nothing        System.out.println("all over 1 crore: " + statuses.stream().allMatch(s -> s.length() > 10_000_000));
        boolean safeAllPaid = !statuses.isEmpty()                && statuses.stream().allMatch(s -> s.equals("SUCCESS"));        System.out.println("safe check: " + safeAllPaid);    }}
Output
allMatch:  true
anyMatch:  false
noneMatch: true
all over 1 crore: true
safe check: false

What this code does

  • With no elements, there is nothing that can fail, so allMatch and noneMatch return true; there is nothing that can pass, so anyMatch returns false. The predicate is never called.
  • When an empty list must mean "no", say so in code: !list.isEmpty() && list.stream().allMatch(...). The && also short-circuits, so the stream is not even created for an empty list.

This is called vacuous truth: "every element passes" is true when there is no element that fails. Logic and maths use the same rule. allMatch looks for one failing element, finds none, and answers true. It becomes a bug when an empty batch means "something went wrong". If the payment file failed to load, allMatch(success) still says true and the report says "all paid". When empty must mean "no", check isEmpty() first, or write !list.isEmpty() && list.stream().allMatch(...).

Predict the output

Predict the empty batch

Each pipeline runs on an empty list. What does it print?

Round 1 of 3

What does this print?

import java.util.List;
public class EmptyAll {
public static void main(String[] args) {
List<Integer> payments = List.of();
System.out.println(payments.stream().allMatch(p -> p > 0));
}
}
Write the empty case into your tests: a check that has only ever seen full lists will hide this bug.

Example 5 · Checking characters: a valid username

UsernameDemo.javaJava
import java.util.List;
public class UsernameDemo {    public static void main(String[] args) {        List<String> names = List.of("rohan_21", "Priya99", "kavya 7", "aarav!");
        for (String name : names) {            boolean lettersDigitsOnly = name.chars()                                            .allMatch(c -> Character.isLetterOrDigit(c) || c == '_');            boolean hasDigit = name.chars().anyMatch(Character::isDigit);            System.out.println(name + " -> valid: " + (lettersDigitsOnly && hasDigit));        }    }}
Output
rohan_21 -> valid: true
Priya99 -> valid: true
kavya 7 -> valid: false
aarav! -> valid: false

What this code does

  • name.chars() gives the characters of a String as a stream of int codes, an IntStream. It has the same allMatch and anyMatch, taking a lambda on int.
  • kavya 7 fails because of the space, and aarav! because of !. allMatch stops at the first bad character, so long strings are rejected quickly.

Next step

Check your understanding

11 quick questions