17.6.6 Counting the Number of Employees in Each Department
Figure 17.15 once again demonstrates Stream
method collect
and Collectors static
method groupingBy
, but in this case we count the number of Employee
s in each department. Lines 107–110 produce a Map<String, Long>
in which each String
key is a department name and the corresponding Long
value is the number of Employee
s in that department. In this case, we use a version of Collectors static
method groupingBy
that receives two arguments—the first is a Function
that classifies the objects in the stream and the second is another Collector
(known as the downstream Collector
). In this case, we use a call to Collectors static
method counting
as the second argument. This method returns a Collector ...
Get Java™ How To Program (Early Objects), Tenth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.