Java Reference
In-Depth Information
Employees by department:
Sales
Matthew Indigo 3587.50 Sales
Jason Blue 3200.00 Sales
IT
Jason Red 5000.00 IT
Ashley Green 7600.00 IT
Luke Indigo 6200.00 IT
Marketing
James Indigo 4700.77 Marketing
Wendy Brown 4236.40 Marketing
Fig. 17.14
|
Grouping
Employee
s by department. (Part 2 of 2.)
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 depart-
ment. Lines 107-110 produce a
Map<String,
Long>
in which each
String
key is a depart-
ment 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
that counts the number of objects in a given classification, rather than
collecting them into a
List
. Lines 111-113 then output the key-value pairs from the re-
sulting
Map<String,
Long>
.
105
// count number of Employees in each department
106
System.out.printf(
"%nCount of Employees by department:%n"
);
107
108
109
110
111
employeeCountByDepartment.forEach(
112
(department, count) -> System.out.printf(
113
"%s has %d employee(s)%n"
, department, count));
114
Map<String, Long> employeeCountByDepartment =
list.stream()
.collect(Collectors.groupingBy(Employee::getDepartment,
Collectors.counting()));
Count of Employees by department:
IT has 3 employee(s)
Marketing has 2 employee(s)
Sales has 2 employee(s)
Fig. 17.15
|
Counting the number of
Employee
s in each department.
Figure 17.16 demonstrates
Stream
method
mapToDouble
(lines 119, 126 and 132), which
maps objects to
double
values and returns a
DoubleStream
. In this case, we map
Employee