CKTIS / Java
IntStream.allMatch(IntPredicate): test whether every element matches
Check whether every `int` in a stream meets a condition, and learn why an empty stream returns `true`.
Version: Java SE 21
Syntax
boolean allMatch(IntPredicate predicate)IntStream.allMatch(IntPredicate) is an instance method of java.util.stream.IntStream. It takes one required java.util.function.IntPredicate argument, such as n -> n % 2 == 0. The predicate takes a primitive int and returns a boolean, so the value does not need to be boxed as an Integer.
The method returns true if every element matches and false if even one does not. An empty stream returns true without calling the predicate: there is no element that fails the test. If your input must be non-empty, check that separately.
This is a short-circuiting terminal operation. One non-matching element is enough to determine that the result is false, so the method may skip testing some elements. The predicate must not modify the source or depend on changing state. Do not rely on side effects such as counting predicate calls.
After allMatch returns, the stream is consumed even if not every element was tested. To check the same data again, create a new stream from the same source.
Examples
import java.util.function.IntPredicate;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
IntPredicate isEven = n -> n % 2 == 0;
System.out.println(IntStream.of(2, 4, 6).allMatch(isEven));
System.out.println(IntStream.of(2, 3, 6).allMatch(isEven));
System.out.println(IntStream.empty().allMatch(isEven));
}
}
Result
true false true
`n % 2 == 0` tests whether the remainder after division by `2` is zero. The first stream contains only even numbers (`true`), `3` fails the test in the second (`false`), and the third stream is empty (`true`). Each call uses a fresh stream.
Related lessons
- Java · Lesson 63 · Basic · Version: 2