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

Java Stream anyMatch() checks if any element matches a predicate. Learn allMatch(), noneMatch(), empty stream results and short-circuiting with examples.

Three rows show anyMatch, allMatch and noneMatch running over the scores 72, 88, 95 and 64 and stopping at the element that decides the result

The Java Stream method anyMatch(predicate) returns true if at least one element of the stream matches the predicate, and false otherwise. Its two siblings work the same way, so allMatch() returns true when every element matches and noneMatch() returns true when no element matches. All three are short-circuiting terminal operations, which means they stop reading the stream as soon as the answer is known.

We use these methods for yes-or-no checks on data, for example to find out whether any order in a batch failed, whether all uploaded files are below a size limit, or whether a password contains none of the blocked words.

The following example runs all three checks on a list of exam scores.

List<Integer> scores = List.of(72, 88, 95, 64);
boolean anyFailed = scores.stream().anyMatch(s -> s < 65);     // true
boolean allPassed = scores.stream().allMatch(s -> s >= 65);    // false
boolean noneZero = scores.stream().noneMatch(s -> s == 0);     // true

Notice that each check opens a new stream from the list, because a stream can run only one terminal operation. In the next sections we look at each method on its own, the surprising result for empty streams, short-circuiting with infinite streams, and how anyMatch() compares with contains().

1. What anyMatch(), allMatch() and noneMatch() Return

All three methods take a Predicate and return a primitive boolean, not an Optional. They differ only in the question they ask about the elements of the Stream, and in the element that lets them stop early.

Three rows show anyMatch, allMatch and noneMatch running over the scores 72, 88, 95 and 64 and stopping at the element that decides the result
Each method stops at the first element that decides the answer, so later elements are never tested

Each signature has the form boolean anyMatch(Predicate<? super T> predicate). The predicate must be non-interfering and stateless, so it must not change the source collection or depend on values that change while the stream runs. The table sums up when each method returns true and where it stops.

MethodReturns true whenStops at the first element thatEmpty stream
anyMatch(p)at least one element matchesmatches (result true)false
allMatch(p)every element matchesdoes not match (result false)true
noneMatch(p)no element matchesmatches (result false)true

2. Checking for at Least One Match With Stream anyMatch()

The method anyMatch() answers the question “is there any element like this?”. It tests the elements in encounter order and returns true at the first match. If no element matches, it has to read the whole stream before it returns false.

The following example uses a small library catalog. Each book is a record with a title, a page count and a flag that says whether the book is on the shelf.

record Book(String title, int pages, boolean available) {}
List<Book> books = List.of(new Book("Dune", 412, true), new Book("Emma", 474, false), new Book("Ulysses", 730, true));
boolean anyLong = books.stream().anyMatch(b -> b.pages() > 700);                // true
boolean anyOnLoan = books.stream().anyMatch(Predicate.not(Book::available));    // true
boolean anyByTitle = books.stream().anyMatch(b -> b.title().equals("Emma"));    // true
boolean anyHuge = books.stream().anyMatch(b -> b.pages() > 1000);               // false

A method reference such as Book::available works as a predicate when the method returns a boolean, and Predicate.not() (Java 11) negates it without writing a lambda.

2.1. Combining Several Conditions

To check several conditions at once, we compose simple predicates with and(), or() and negate(). Named predicates keep the stream line short and let us reuse each condition in other checks.

List<Book> books = List.of(new Book("Dune", 412, true), new Book("Emma", 474, false), new Book("Ulysses", 730, true));
Predicate<Book> longBook = b -> b.pages() > 450;
Predicate<Book> onShelf = Book::available;
boolean longAndOnShelf = books.stream().anyMatch(longBook.and(onShelf));             // true
boolean shortAndOnLoan = books.stream().anyMatch(longBook.negate().and(onShelf.negate()));   // false

The first check finds Ulysses, which has 730 pages and is available. The second check finds nothing, because the only book on loan, Emma, has more than 450 pages.

3. Requiring Every Element to Match With allMatch()

The method allMatch() answers “does every element pass?”. It returns false at the first element that fails the predicate, so a list with one bad entry near the start is checked fast. To return true, it has to test every element.

List<Book> books = List.of(new Book("Dune", 412, true), new Book("Emma", 474, false), new Book("Ulysses", 730, true));
boolean allOver400 = books.stream().allMatch(b -> b.pages() > 400);       // true
boolean allAvailable = books.stream().allMatch(Book::available);          // false
boolean allTitled = books.stream().allMatch(b -> !b.title().isBlank());   // true

A typical use is input validation. A bulk import accepts a file only if every row passes the checks, and an admin screen enables the “Close month” button only if all invoices of that month are paid.

4. Confirming That No Element Matches With noneMatch()

The method noneMatch() answers “is there no element like this?”. It returns false at the first match and true only after testing every element. It reads better than a negated anyMatch() when the condition describes something we do not want, such as a blocked word or an error status.

List<Book> books = List.of(new Book("Dune", 412, true), new Book("Emma", 474, false), new Book("Ulysses", 730, true));
boolean noneHuge = books.stream().noneMatch(b -> b.pages() > 1000);           // true
boolean noneOnLoan = books.stream().noneMatch(Predicate.not(Book::available));  // false

The three methods are linked by simple logic, so every check can be written in the other two forms. For a predicate p, noneMatch(p) gives the same result as !anyMatch(p) and as allMatch(Predicate.not(p)).

List<Integer> scores = List.of(72, 88, 95, 64);
Predicate<Integer> failed = s -> s < 65;
boolean viaNone = scores.stream().noneMatch(failed);                  // false
boolean viaAny = !scores.stream().anyMatch(failed);                   // false
boolean viaAll = scores.stream().allMatch(Predicate.not(failed));     // false

We pick the form whose predicate reads as a positive condition, because a double negation such as !noneMatch(not(p)) is where logic bugs hide.

4.1. Checking Strings for Digits

A common mistake is to check for digits with s.contains(“\\d+”). The method String.contains() searches for literal text, not a regular expression, so that check looks for a backslash followed by d+ and never finds a digit. We test characters with Character.isDigit() or use matches() with a real regex.

List<String> codes = List.of("one", "two", "a1");
boolean wrongCheck = codes.stream().noneMatch(s -> s.contains("\\d+"));                  // true, contains() is not a regex
boolean noDigits = codes.stream().noneMatch(s -> s.chars().anyMatch(Character::isDigit));  // false
boolean noDigitsRegex = codes.stream().noneMatch(s -> s.matches(".*\\d.*"));              // false

5. Why allMatch() and noneMatch() Return true for an Empty Stream

On an empty stream, anyMatch() returns false, whereas allMatch() and noneMatch() both return true. The predicate is never called. Logic calls this rule vacuous truth. “All elements are below 5 MB” is true for zero elements, because there is no element that breaks the rule.

List<Integer> uploadSizes = List.of();
boolean anyLarge = uploadSizes.stream().anyMatch(s -> s > 5_000);                                  // false
boolean allSmall = uploadSizes.stream().allMatch(s -> s < 5_000);                                  // true
boolean noneLarge = uploadSizes.stream().noneMatch(s -> s > 5_000);                                // true
boolean validUpload = !uploadSizes.isEmpty() && uploadSizes.stream().allMatch(s -> s < 5_000);     // false

The result is logically correct, but it causes real bugs. Say an upload form checks allMatch(size < limit) before saving. A request with no files passes the check, and the app saves an empty upload. When “nothing to check” must fail, we add an isEmpty() check as in the last line.

6. Short-Circuiting and Infinite Streams

A short-circuiting terminal operation can finish in finite time even when the input is infinite. We can see where the matching stops with peek(), which records every element that reaches the match step.

List<Integer> tested = new ArrayList<>();
boolean found = Stream.of(72, 88, 95, 64).peek(tested::add).anyMatch(s -> s > 80);   // true
List<Integer> visited = List.copyOf(tested);                                         // [72, 88]

The stream stopped at 88, so 95 and 64 never reached the predicate. The same rule lets the methods work on an infinite stream, as long as the deciding element appears at some point.

boolean hasBig = Stream.iterate(1, n -> n * 2).anyMatch(n -> n > 1000);     // true, stops at 1024
boolean allSmall = Stream.iterate(1, n -> n * 2).allMatch(n -> n < 1000);   // false, stops at 1024

If the deciding element never comes, the call never returns. For example, Stream.iterate(1, n -> n * 2).noneMatch(n -> n == 3) runs forever, because no power of two equals 3. With an infinite source, we bound the stream with limit() or takeWhile() before matching.

In a parallel stream, the methods still return the same result, but several threads test elements at the same time. The predicate can run on elements after the deciding one, and in any order, so a predicate with side effects such as logging or counting gives different output from run to run. A parallel stream gains nothing for small lists, because coordinating the threads costs more than the checks themselves.

7. anyMatch() Compared With contains() and findFirst()

For a collection we already hold, contains() is shorter, but it can only test equality with equals(). The method anyMatch() accepts any condition, such as a case-insensitive comparison, a field of a record or a range check. The stream also has no contains() method of its own, which the stream contains guide covers in detail.

List<String> tags = List.of("java", "spring", "sql");
boolean hasJava = tags.contains("java");                                                 // true
boolean hasUpper = tags.contains("JAVA");                                                // false
boolean hasIgnoreCase = tags.stream().anyMatch("JAVA"::equalsIgnoreCase);                // true
boolean viaFilter = tags.stream().filter(t -> t.startsWith("s")).findFirst().isPresent();  // true

The last line returns the same result as anyMatch(t -> t.startsWith(“s”)), and both stop at the first match. We use filter() with findFirst() only when we need the matching element itself, as shown in the findFirst() and findAny() guide. For a yes-or-no question, anyMatch() says what we mean.

NeedUse
Is this exact value in my list or set?collection.contains(value)
Does any element meet a condition?stream.anyMatch(p)
Which element meets the condition?stream.filter(p).findFirst()
How many elements meet the condition?stream.filter(p).count()

8. Matching on IntStream and Map Values

The primitive streams IntStream, LongStream and DoubleStream have the same three methods with IntPredicate, LongPredicate and DoublePredicate, so no boxing happens. A Map has no stream of its own, so we stream its values(), keySet() or entrySet().

int[] ratings = {4, 5, 3, 5};
boolean allValid = Arrays.stream(ratings).allMatch(r -> r >= 1 && r <= 5);    // true
boolean anyPerfect = IntStream.of(ratings).anyMatch(r -> r == 5);             // true
Map<String, Integer> stock = Map.of("pens", 40, "notebooks", 0, "folders", 12);
boolean anyEmpty = stock.values().stream().anyMatch(q -> q == 0);             // true
boolean noneNegative = stock.values().stream().noneMatch(q -> q < 0);         // true

9. Real-World Example With Password Rules

A sign-up form has to check a new password against several rules and tell the user which rules failed. We keep each rule as a record with a message and a predicate, so allMatch() gives the overall answer and the same list produces the error messages.

record Rule(String message, Predicate<String> check) {}
List<Rule> rules = List.of(
        new Rule("at least 12 characters", p -> p.length() >= 12),
        new Rule("a digit", p -> p.chars().anyMatch(Character::isDigit)),
        new Rule("an uppercase letter", p -> p.chars().anyMatch(Character::isUpperCase)));
List<String> blockedWords = List.of("password", "qwerty");
String password = "riverside7";
boolean strong = rules.stream().allMatch(r -> r.check().test(password));                        // false
List<String> missing = rules.stream().filter(r -> !r.check().test(password)).map(Rule::message).toList();   // [at least 12 characters, an uppercase letter]
boolean noBlockedWord = blockedWords.stream().noneMatch(w -> password.toLowerCase(Locale.ROOT).contains(w));   // true

Adding a rule means adding one line to the list, and the validation code does not change. The same pattern fits order checks in a shop, such as “every line has a positive quantity” and “no line references a discontinued item”.

10. Stream Matching FAQs

Searchers who use the matching methods for the first time ask most often about empty input, reuse, speed and the Java version.

10.1. Does anyMatch() return false for an empty stream?

Yes. With no elements, nothing can match, so anyMatch() returns false without calling the predicate. The methods allMatch() and noneMatch() return true on an empty stream, as explained in section 5.

10.2. Is noneMatch() the opposite of allMatch()?

No. The opposite of noneMatch(p) is anyMatch(p). A list of scores [72, 40] with the predicate “score below 65” gives false for both allMatch() and noneMatch(), because some scores match and some do not.

10.3. Can we call anyMatch() twice on the same stream?

No. A stream runs one terminal operation, and the second call throws an IllegalStateException. We create a new stream from the source for each check, or keep the data in a list. The stream has already been operated upon or closed article covers the error in detail.

Stream<String> titles = Stream.of("Dune", "Emma");
boolean first = titles.anyMatch(t -> t.startsWith("D"));     // true
boolean second = titles.anyMatch(t -> t.startsWith("E"));    // IllegalStateException: stream has already been operated upon or closed

10.4. Is anyMatch() faster than a for loop?

Not in a measurable way for typical lists. Both stop at the first match and test the same elements, so the difference is the small setup cost of the stream. We choose by readability, and a loop is fine when the body needs break with extra work or checked exceptions.

10.5. Which Java version added anyMatch(), allMatch() and noneMatch()?

All three came with the Stream API in Java 8 and have not changed since. The helpers we combine them with are newer, such as Predicate.not() from Java 11 and Stream.toList() from Java 16.

11. Conclusion

The methods anyMatch(), allMatch() and noneMatch() turn a stream into one boolean. Each stops at the first element that decides the answer, which also makes them safe on infinite streams whenever a deciding element exists.

The one rule to remember is the empty stream. There anyMatch() returns false while the other two return true, so validation code that must reject empty input needs its own isEmpty() check. For plain equality on a collection, contains() stays the shorter choice.

12. References

Happy Learning !!

Source Code on Github

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.