Java Stream count() Matches with filter()

Learn to count the matching items in the Stream that are passed by a specified filter expression. To count the items, we can use the following two methods and both are terminal operations and will give the same result.

  • Stream.count()
  • Stream.collect(Collectors.counting())

1. Stream count() API

The Stream interface has a default method called count() that returns a long value indicating the number of matching items in the stream.

long count()

To use the count() method, call it on any Stream instance.

Stream s = ...;


2. Counting Matches in Stream

Example 1: Counting all items in the Stream

In this example, we are counting the number of elements in different kinds of streams such as IntStream, LongStream.

long count = Stream.of("how","to","do","in","java").count();	//5
long count = IntStream.of(1,2,3,4,5,6,7,8,9).count();   //9

Example 2: Counting items matching to Stream filter()

To count the matching items, we need to apply a filter expression or predicate to filter that will find the matching items and then we can use count() API to count the items.

In the given example, we are counting all the even numbers in the stream.

long count = LongStream.of(1,2,3,4,5,6,7,8,9)
            .filter(i -> i%2 == 0)

Happy Learning !!

Sourcecode on Github

Leave a Reply

Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial