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.
long count();
This method returns the number of elements on the stream as a long
value.
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 filter
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.