Java Reference
In-Depth Information
Unique employee last names:
Blue
Brown
Green
Indigo
Red
Employee names in order by last name then first name:
Jason Blue
Wendy Brown
Ashley Green
James Indigo
Luke Indigo
Matthew Indigo
Jason Red
Fig. 17.13
|
Mapping
Employee
objects to last names and whole names. (Part 2 of 2.)
Figure 17.14 uses
Stream
method
collect
(line 95) to group
Employees
by department.
Method
collect
's argument is a
Collector
that specifies how to summarize the data into
a useful form. In this case, we use the
Collector
returned by
Collectors
static
method
groupingBy
, which receives a
Function
that classifies the objects in the stream—the values
returned by this function are used as the keys in a
Map
. The corresponding values, by de-
fault, are
List
s containing the stream elements in a given category. When method
col-
lect
is used with this
Collector
, the result is a
Map<String,
List<Employee>>
in which
each
String
key is a department and each
List<Employee>
contains the
Employee
s in that
department. We assign this
Map
to variable
groupedByDepartment
, which is used in lines
96-103 to display the
Employees
grouped by department.
Map
method
forEach
performs
an operation on each of the
Map
's key-value pairs. The argument to the method is an ob-
ject that implements functional interface
BiConsumer
. This interface's
accept
method has
two parameters. For
Map
s, the first parameter represents the key and the second represents
the corresponding value.
91
// group Employees by department
92
System.out.printf(
"%nEmployees by department:%n"
);
93
94
95
96
groupedByDepartment.forEach(
97
98
99
100
101
102
103
);
104
Map<String, List<Employee>> groupedByDepartment =
list.stream()
.collect(Collectors.groupingBy(Employee::getDepartment));
(department, employeesInDepartment) ->
{
System.out.println(department);
employeesInDepartment.forEach(
employee -> System.out.printf(
" %s%n"
, employee));
}
Fig. 17.14
|
Grouping
Employee
s by department. (Part 1 of 2.)