Java Reference
In-Depth Information
them by first name. To do so, we begin by creating two Function s that each receive an
Employee and return a String :
byFirstName (line 54) is assigned a method reference for Employee instance
method getFirstName
byLastName (line 55) is assigned a method reference for Employee instance meth-
od getLastName
Next, we use these Function s to create a Comparator ( lastThenFirst ; lines 58-59) that
first compares two Employee s by last name, then compares them by first name. We use
Comparator method comparing to create a Comparator that calls Function byLastName
on an Employee to get its last name. On the resulting Comparator , we call Comparator
method thenComparing to create a Comparator that first compares Employee s by last name
and, if the last names are equal , then compares them by first name. Lines 64-65 use this
new lastThenFirst Comparator to sort the Employee s in ascending order, then display the
results. We reuse the Comparator in lines 71-73, but call its reversed method to indicate
that the Employee s should be sorted in descending order by last name, then first name.
53
// Functions for getting first and last names from an Employee
54
Function<Employee, String> byFirstName = Employee::getFirstName;
Function<Employee, String> byLastName = Employee::getLastName;
55
56
57
// Comparator for comparing Employees by first name then last name
58
Comparator<Employee> lastThenFirst =
Comparator.comparing(byLastName).thenComparing(byFirstName);
59
60
61
// sort employees by last name, then first name
62
System.out.printf(
63
"%nEmployees in ascending order by last name then first:%n" );
64
list.stream()
65
.sorted(lastThenFirst)
66
.forEach(System.out::println);
67
68
// sort employees in descending order by last name, then first name
69
System.out.printf(
70
"%nEmployees in descending order by last name then first:%n" );
71
list.stream()
72
.sorted(
lastThenFirst.reversed()
)
73
.forEach(System.out::println);
74
Employees in ascending order by last name then first:
Jason Blue 3200.00 Sales
Wendy Brown 4236.40 Marketing
Ashley Green 7600.00 IT
James Indigo 4700.77 Marketing
Luke Indigo 6200.00 IT
Matthew Indigo 3587.50 Sales
Jason Red 5000.00 IT
Fig. 17.12 | Sorting Employee s by last name then first name. (Part 1 of 2.)
 
Search WWH ::




Custom Search