Java Reference
In-Depth Information
Employees in descending order by last name then first:
Jason Red 5000.00 IT
Matthew Indigo 3587.50 Sales
Luke Indigo 6200.00 IT
James Indigo 4700.77 Marketing
Ashley Green 7600.00 IT
Wendy Brown 4236.40 Marketing
Jason Blue 3200.00 Sales
Fig. 17.12 | Sorting Employee s by last name then first name. (Part 2 of 2.)
17.6.4 Mapping Employee s to Unique Last Name String s
You previously used map operations to perform calculations on int values and to convert
String s to uppercase letters. In both cases, the resulting streams contained values of the same
types as the original streams. Figure 17.13 shows how to map objects of one type ( Employee )
to objects of a different type ( String ). Lines 77-81 perform the following tasks:
• Line 77 creates a Stream<Employee> .
• Line 78 maps the Employees to their last names using the instance method refer-
ence Employee::getName as method map 's Function argument. The result is a
Stream<String> .
• Line 79 calls Stream method distinct on the Stream<String> to eliminate any
duplicate String objects in a Stream<String> .
• Line 80 sorts the unique last names.
• Finally, line 81 performs a terminal forEach operation that processes the stream
pipeline and outputs the unique last names in sorted order.
Lines 86-89 sort the Employees by last name then first name, then map the Employee s to
String s with Employee instance method getName (line 88) and display the sorted names
in a terminal forEach operation.
75
// display unique employee last names sorted
76
System.out.printf( "%nUnique employee last names:%n" );
77
list.stream()
78
.map(Employee::getLastName)
.distinct()
79
80
.sorted()
81
.forEach(System.out::println);
82
83
// display only first and last names
84
System.out.printf(
85
"%nEmployee names in order by last name then first name:%n" );
86
list.stream()
87
.sorted(lastThenFirst)
88
.map(Employee::getName)
89
.forEach(System.out::println);
90
Fig. 17.13 | Mapping Employee objects to last names and whole names. (Part 1 of 2.)
 
 
Search WWH ::




Custom Search