CKTIS / Java
IntStream.count — counting stream elements
IntStream.count() returns the number of elements as a long, not the sum of their values. It is a terminal operation that counts elements remaining after earlier operations such as filter.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
long count = intStream.count();IntStream.count() takes no arguments and returns a long, even though the stream elements have type int. An empty stream produces 0. Repeated values count separately: the method neither removes duplicates nor adds up values.
This is a terminal operation that completes the pipeline. It counts elements after earlier intermediate operations, such as filter. Do not reuse the same stream afterward; create a new stream for another computation. Do not apply count() to an unbounded infinite stream expecting it to terminate.
The implementation may compute the count without traversing elements when it knows the size from the source. It may then skip intermediate operations, so do not rely on side effects in peek or map.
In the example, filter retains 2, 4, 4, so the result is 3. Both occurrences of 4 count separately.
Examples
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
long count = IntStream.of(2, 3, 4, 4, 7)
.filter(n -> n % 2 == 0)
.count();
System.out.println(count);
}
}Result
3
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.