Hi everyone.
Welcome back to this tutorial.
In this tutorial we will code and explore the counting Collector as part of this tutorial.
The name counting collector returns the total number of elements the collector collected as a result.
Let's go ahead and explore this.
Using our example app.
Then you open here what I'm going to do.
I'm going to create a class called Streams Counting example.
Make this class executable by adding public static void main method and then put this in presentation
mode.
So here what I'm going to do, I'm going to create a method called public static.
The counting method returns a type long and then I'm going to name this one as count.
The first call that I'm going to make is student database dot get all students.
The next one is let's call the stream method.
Want to give us a stream of students for us and then we're going to use the collect.
And we are going to use counting.
Basically, we have to do a static import of counting.
There you go.
Collectors dot counting.
We do a return.
This is going to return total number of elements that reach the collect method.
But we are we know by now here we don't have any conditions.
Whatever the values that are written here, whatever the number of students that are returned here will
be, the value that the count is going to return.
You might be wondering, okay, there is no special case.
I can do that by using the get all student dot size that is going to do the same, Right?
But we can add some enhancements to it so that it will make more sense on scenarios when you can use
counting.
So I'm going to print this.
Let's call this count method run.
This is going to give me the result as six because the get all student has a total of six students.
Now let's enhance this use case.
How can we enhance this?
Let's say I want to filter the students by their GPA.
Student dot.
Get GPA greater than or equal to 3.9.
The students who are as the GPA greater than 3.9 are the students, which will cross this filter layer
and reach the collect method.
Let's run this example and then check what is the result of the count method.
The result is three.
So under what scenarios you might use counting.
Let's say you have a use case you want to check.
You have this many number of elements.
Filter this many number of elements matching this criteria.
In those kind of scenarios, you can use the counting method.
So this is all about the counting collector method.
With this, we came to the end of this tutorial.
Thank you for watching.