anyMatch(), allMatch() and noneMatch()
Answer yes-or-no questions about a stream with short-circuiting checks, and remember what each returns for an empty stream.
boolean anyMatch(Predicate<? super T> predicate)
boolean allMatch(Predicate<? super T> predicate)
boolean noneMatch(Predicate<? super T> predicate)- Added in Java Java 8
Parameters
| Parameter | Type | Description |
|---|---|---|
$predicate | Predicate<? super T> | A non-interfering, stateless test applied to elements until the answer is known. |
Return value
booleananyMatch: true if at least one element matches. allMatch: true if every element matches, or the stream is empty. noneMatch: true if no element matches, or the stream is empty.
Errors
Nothing directly. Exceptions thrown by the predicate surface directly.
These three terminal operations answer a yes-or-no question about the elements and return a boolean. They are short-circuiting: they stop reading as soon as the answer is known, so they never need to visit more elements than necessary.
| Method | True when | Stops at | Empty stream |
|---|---|---|---|
anyMatch(p) | at least one element matches | first match | false |
allMatch(p) | every element matches | first non-match | true |
noneMatch(p) | no element matches | first match | true |
The empty-stream rule
allMatch on an empty stream returns true, because there is no element that fails. Logicians call this vacuous truth; in a service it is a bug waiting to happen. "Can this basket check out? Every item is in stock" is true for an empty basket. "Is the user allowed? All required checks pass" is true if the list of checks failed to load. When an empty input should mean no, test for it explicitly: !items.isEmpty() && items.stream().allMatch(...).
Use them instead of counting or finding
filter(p).count() > 0visits everything;anyMatch(p)stops at the first hit.filter(p).findFirst().isPresent()works but says less;anyMatch(p)states the intent.!anyMatch(p)is the same asnoneMatch(p); pick whichever reads naturally.- For a plain equality check on a collection,
list.contains(x)orset.contains(x)is simpler, and aHashSetlookup does not scan at all.
Back-end uses
Authorisation checks are a natural fit: required.stream().anyMatch(userRoles::contains) asks whether the user has any of the roles an endpoint accepts, and allMatch asks whether they have all of them. Validation is another: lines.stream().noneMatch(String::isBlank). Put the cheapest or most likely-to-decide check first when you combine predicates, since evaluation stops early.
Short-circuiting also makes these safe on infinite streams, as long as the answer is eventually found. Stream.iterate(1, n -> n + 1).anyMatch(n -> n > 5) returns true; allMatch(n -> n > 0) on the same stream would never finish.
Example
When to use it
- Allow access to an admin endpoint when the user holds any one of the accepted roles.
- Reject an uploaded file when any line fails validation, stopping at the first bad line.
- Confirm every item in a basket is in stock before creating an order, with an explicit empty-basket check.
Frequently asked questions
Why does allMatch return true for an empty list?
allMatch asks whether any element fails the predicate. With no elements, nothing fails, so the answer is true. If an empty list should count as a failure in your rule, check isEmpty() before calling allMatch.
How do I check if a list contains an element matching a condition?
Use list.stream().anyMatch(condition). It returns true at the first match without reading the rest. For an exact value, list.contains(value) is simpler.
Is noneMatch the same as !anyMatch?
Yes, noneMatch(p) always gives the same result as !anyMatch(p), including true for an empty stream. Use whichever makes the condition read naturally.
More examples
Role checks for an endpoint
Streaming over the short list of required roles and checking each against a Set keeps every lookup cheap. anyMatch, allMatch and noneMatch map directly onto 'has one of', 'has all of' and 'has none of'.
void main() {
Set<String> userRoles = Set.of("editor", "viewer");
List<String> anyOf = List.of("admin", "editor");
IO.println("any of " + anyOf + ": " + anyOf.stream().anyMatch(userRoles::contains));
IO.println("all of " + anyOf + ": " + anyOf.stream().allMatch(userRoles::contains));
List<String> banned = List.of("suspended", "locked");
IO.println("none banned: " + banned.stream().noneMatch(userRoles::contains));
}
// Output:
// any of [admin, editor]: true
// all of [admin, editor]: false
// none banned: trueallMatch stops at the first failure
Once one element fails, the answer is false, so the third address is never checked. Put expensive checks behind cheap ones for the same reason.
void main() {
boolean allValid = Stream.of("[email protected]", "not-an-email", "[email protected]")
.allMatch(s -> {
IO.println("checking " + s);
return s.contains("@");
});
IO.println(allValid);
}
// Output:
// checking [email protected]
// checking not-an-email
// falseGuarding against the empty case
allMatch alone would let an empty basket through. The isEmpty check makes the business rule explicit: there must be items, and every item must be in stock.
boolean canCheckout(List<Integer> stockLevels) {
return !stockLevels.isEmpty() && stockLevels.stream().allMatch(s -> s > 0);
}
void main() {
IO.println(List.<Integer>of().stream().allMatch(s -> s > 0));
IO.println(canCheckout(List.of()));
IO.println(canCheckout(List.of(3, 1)));
IO.println(canCheckout(List.of(3, 0)));
}
// Output:
// true
// false
// true
// false
Discussion