anyMatch, allMatch and noneMatch
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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)); }}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 aboolean. The one lineanyMatch(m -> m < 35)replaces the flag, the loop, theifand thebreak. - 29 is below 35, so
anyMatchis true andallMatchis false. No mark is above 100, sononeMatch(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):trueif at least one element passesp.allMatch(p):trueif every element passesp.noneMatch(p):trueif no element passesp.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".
Example 2 · Short-circuiting traced step by step
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); }}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
anyMatchstops at 91, the first mark that passes, so 64 and 29 are never checked.allMatchstops at 38, the first mark that fails.noneMatchmust 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?
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())); } }}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
booleanvalues, ready for anif. - A match operation only answers yes or no. To know which payment failed, use
filterwithforEachortoList.
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"
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); }}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
allMatchandnoneMatchreturntrue; there is nothing that can pass, soanyMatchreturnsfalse. 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?
Example 5 · Checking characters: a valid username
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)); } }}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 ofintcodes, anIntStream. It has the sameallMatchandanyMatch, taking a lambda onint.kavya 7fails because of the space, andaarav!because of!.allMatchstops at the first bad character, so long strings are rejected quickly.
Next step
Check your understanding
11 quick questions