Java Reference
In-Depth Information
33
// Predicate that returns true for salaries in the range $4000-$6000
34
Predicate<Employee> fourToSixThousand =
e -> (e.getSalary() >=
4000
&& e.getSalary() <=
6000
);
35
36
37
// Display Employees with salaries in the range $4000-$6000
38
// sorted into ascending order by salary
39
System.out.printf(
40
"%nEmployees earning $4000-$6000 per month sorted by salary:%n"
);
41
list.stream()
.filter(fourToSixThousand)
.sorted(Comparator.comparing(Employee::getSalary))
.forEach(System.out::println);
42
43
44
45
46
// Display first Employee with salary in the range $4000-$6000
47
System.out.printf(
"%nFirst employee who earns $4000-$6000:%n%s%n"
,
48
list.stream()
49
.filter(fourToSixThousand)
50
.findFirst()
.get()
51
);
52
Employees earning $4000-$6000 per month sorted by salary:
Wendy Brown 4236.40 Marketing
James Indigo 4700.77 Marketing
Jason Red 5000.00 IT
First employee who earns $4000-$6000:
Jason Red 5000.00 IT
Fig. 17.11
|
Filtering
Employee
s with salaries in the range $4000-$6000.
Short-Circuit Stream Pipeline Processing
In Section 5.9, you studied short-circuit evaluation with the logical AND (
&&
) and logical
OR (
||
) operators. One of the nice performance features of lazy evaluation is the ability
to perform
short
circuit evaluation
—that is, to stop processing the stream pipeline as soon
as the desired result is available. Line 50 demonstrates
Stream
method
findFirst
—a
short-circuiting terminal operation
that processes the stream pipeline and terminates pro-
cessing as soon as the
first
object from the stream pipeline is found. Based on the original
list of
Employee
s, the processing of the stream in lines 48-51—which filters
Employee
s
with salaries in the range $4000-$6000—proceeds as follows: The
Predicate
fourTo-
SixThousand
is applied to the first
Employee
(Jason Red). His salary ($5000.00) is in the
range $4000-$6000, so the
Predicate
returns
true
and processing of the stream termi-
nates
immediately
, having processed only one of the eight objects in the stream. Method
findFirst
then returns an
Optional
(in this case, an
Optional<Employee>
) containing
the object that was found, if any. The call to
Optional
method
get
(line 51) returns the
matching
Employee
object in this example. Even if the stream contained millions of
Em-
ployee
objects, the
filter
operation would be performed only until a match is found.
Figure 17.12 shows how to use streams to sort objects by
multiple
fields. In this example,
we sort
Employee
s by last name, then, for
Employee
s with the same last name, we also sort