Java Reference
In-Depth Information
28
29
// display all Employees
30
System.out.println(
"Complete Employee list:"
);
31
list.stream().forEach(System.out::println);
32
Complete Employee list:
Jason Red 5000.00 IT
Ashley Green 7600.00 IT
Matthew Indigo 3587.50 Sales
James Indigo 4700.77 Marketing
Luke Indigo 6200.00 IT
Jason Blue 3200.00 Sales
Wendy Brown 4236.40 Marketing
Fig. 17.10
|
Creating an array of
Employee
s, converting it to a
List
and displaying the
List
.
(Part 2 of 2.)
Line 31 creates a
Stream<Employee>
, then uses
Stream
method
forEach
to display each
Employee
's
String
representation. The instance method reference
System.out::println
is
converted by the compiler into an object that implements the
Consumer
functional interface.
This interface's
accept
method receives one argument and returns
void
. In this example, the
accept
method passes each
Employee
to the
System.out
object's
println
instance method,
which implicitly calls class
Employee
's
toString
method to get the
String
representation.
The output at the end of Fig. 17.10 shows the results of displaying all the
Employee
s.
Figure 17.11 demonstrates filtering
Employee
s with an object that implements the func-
tional interface
Predicate<Employee>
, which is defined with a lambda in lines 34-35.
Defining lambdas in this manner enables you to reuse them multiple times, as we do in
lines 42 and 49. Lines 41-44 output the
Employee
s with salaries in the range 4000-6000
sorted by salary as follows:
•
Line 41 creates a
Stream<Employee>
from the
List<Employee>
.
•
Line 42 filters the stream using the
Predicate
named
fourToSixThousand
.
•
Line 43 sorts by salary the
Employees
that remain in the stream. To specify a
Com-
parator
for salaries, we use the
Comparator
interface's
static
method
compar-
ing
. The method reference
Employee::getSalary
that's passed as an argument
is converted by the compiler into an object that implements the
Function
inter-
face. This
Function
is used to extract a value from an object in the stream for use
in comparisons. Method
comparing
returns a
Comparator
object that calls
get-
Salary
on each of two
Employee
objects, then returns a negative value if the first
Employee
's salary is less than the second, 0 if they're equal and a positive value if
the first
Employee
's salary is greater than the second.
•
Finally, line 44 performs the terminal
forEach
operation that processes the
stream pipeline and outputs the
Employees
sorted by salary.