Java Stream count() Method Tutorial

In this section, we will learn what the Stream count() method is and how to use it in Java.

What is Java Stream count() Method?

The Java Stream count() method is used to count the number of elements in a Stream.

Note: this method is terminal and after calling the method, there won’t be any more stream.

Java count() Method Syntax:

long count()

count() Method Parameters:

The method does not take an argument.

count() Method Return Value:

The return value of this method is of type long and is equal to the number of elements in the target stream.

count() Method Exceptions:

The method does not throw an exception.

Example: using Stream count() method

import java.util.stream.Stream;
class Main{
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9,10,3,23,4,23,423,2,34,56,7,86,54,5);
        System.out.println(stream.count());
    }
}

Output:

22

As you can see, calling the count() method counted the number of elements in the stream and returned that as a result.

Leave a Reply