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.
1. Stream count() API
Stream interface has a default method called
count() that returns a
long value indicating the number of matching items in the stream.
To use the count() method, call it on any Stream instance.
Stream s = ...; s.count(); //or s.collect(Collectors.counting());
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
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) .count(); //or //.collect(Collectors.counting())
Happy Learning !!