How to check if all elements match a condition
Short answer
allMatch() returns true if the condition holds for every element:
void main() {
var ages = List.of(21, 34, 19);
IO.println(ages.stream().allMatch(age -> age >= 18));
IO.println(ages.stream().allMatch(age -> age >= 20));
}Output:
true
falseAt least one and none
anyMatch() checks that at least one element matches, noneMatch() that none do:
void main() {
var passwords = List.of("secret1", "qwerty", "Tr0ub4dor");
IO.println(passwords.stream().anyMatch(p -> p.length() > 8));
IO.println(passwords.stream().noneMatch(String::isBlank));
}Output:
true
trueStopping at the first answer
These methods stop checking as soon as the answer is known:
void main() {
boolean result = Stream.of(1, 2, 3, 4)
.peek(n -> IO.println("checking " + n))
.allMatch(n -> n < 2);
IO.println(result);
}Output:
checking 1
checking 2
falseCommon mistake
Forgetting about an empty list. allMatch() returns true for an empty stream, and anyMatch() returns false:
void main() {
List<Integer> empty = List.of();
IO.println(empty.stream().allMatch(n -> n > 100));
IO.println(empty.stream().anyMatch(n -> n > 100));
}Output:
true
falseIf an empty list should give false, check !list.isEmpty() separately.
Functions used in this recipe
- Stream.allMatch() — Checks whether all elements match a condition.
- Stream.anyMatch() — Checks whether at least one element matches a condition.
- Stream.noneMatch() — Checks that no element matches a condition.