Java 8 Counting with Collectors tutorial explains, with examples, how to use the predefined
Collector returned by
counting() method to count the number of elements in a
Stream. The tutorial starts off with the formal definition of the
Collectors.counting() method, then explains its working, and finally shows the method’s usage via a Java code example.
(Note – This tutorial assumes that you are familiar with basics of Java 8 CollectorsRead Tutorial explaining basics of Java 8 Collectors.)
Collector returned by
Collectors.counting() method is defined with the following signature –
public static <T> Collector<T, ?, Long> counting()
– output is a
Collector, acting on a Stream of elements of type
T, with its finisherClick to Read tutorial on 4 components of Collectors incl. ‘finisher’ returning the ‘collected’ value of type
The working of the counting collector is pretty straightforward. It is a terminal operationClick to Read Tutorial explaining intermediate & terminal Stream operations which returns the total count of elements in the stream which reach the
collect() method after undergoing various pipelinedClick to Read Tutorial explaining concept of Pipelines in Computing stream operations such as filtering, reduction etc.
It’s also worthwhile to know that internally the counting collector actually delegates the counting job to the ‘reducing collector’ with the call
reducing(0L, e -> 1L, Long::sum). But this call is internal to the implementation and need not be taken into consideration before terminating your stream with the counting Collector.
Java 8 code example showing
Collector.counting() method’s usage
Employee.javais the POJO class i.e. the type of which the Stream is created.
CountingWithCollectorsclass contains a static list of 5
- In the
CountingWithCollectorsclass a stream of
Employeeobjects is created by invoking
employeeList.stream(). This stream is then terminated by invoking the
collect()method with the
Collectorreturned by the
Collectors.counting()method passed as a parameter.
- As expected, the Stream terminates and the counting
Collectorreturns the count of the stream elements(employees) as a
- Lastly, the employee count is printed and is
In this tutorial we understood the working of the predefined
Collector returned by the
Collectors.counting() method. We looked at the formal definition of the
Collectors.counting() method, had a brief look at what actually happens inside the method, and finally saw the
Collectors.counting() method in action with a Java 8 code example and its explanation.