What is the count() method of the Stream Interface?

count() is a default method present in the Stream Interface that will return the number of elements in the stream.

Because the count() method is a terminal operation, the stream cannot be accessed after the count() method is called.

Syntax

long count();

This method returns the number of elements on the stream as a long value.

Example

import java.util.stream.Stream;
public class CountExample {
public static void main(String[] args) {
long count = Stream.of(1,2,3,4,5,6,7,8,9)
.count();
System.out.println("The number of elements in the stream is " + count);
count = Stream.of(1,2,3,4,5,6,7,8,9)
.filter(i -> i%2 == 0)
.count();
System.out.println("The total even numbers in the stream is " + count);
}
}

In the code above, we instantiated a Stream of numbers, then called the count method on the stream. The count method will return a number of elements in the stream.

We created one more stream with numbers, and called the filterThe filter() method is an intermediate operation that filters the elements on this stream based on the given condition. The elements which satisfy the given condition are returned as a new stream. method to get a stream of even numbers. Then, we called the count method, which will return the number of elements in the stream returned from the filter method.

Free Resources