Java Reference
In-Depth Information
17.5.2 Filtering String s Then Sorting Them in Case-Insensitive
Ascending Order
Lines 24-28 filter and sort the String s. Line 25 creates a Stream<String> from the array
strings , then line 26 calls Stream method filter to locate all the String s that are greater
than "m" , using a case-insensitive comparison in the Predicate lambda. Line 27 sorts the
results and line 28 collects them into a List<String> that we output as a String . In this
case, line 27 invokes the version of Stream method sorted that receives a Comparator as
an argument. As you learned in Section 16.7.1, a Comparator defines a compare method
that returns a negative value if the first value being compared is less than the second, 0 if
they're equal and a positive value if the first value is greater than the second. By default,
method sorted uses the natural order for the type—for String s, the natural order is case
sensitive, which means that "Z" is less than "a" . Passing the predefined Comparator
String.CASE_INSENSITIVE_ORDER performs a case-insensitive sort.
17.5.3 Filtering String s Then Sorting Them in Case-Insensitive
Descending Order
Lines 31-35 perform the same tasks as lines 24-28, but sort the String s in descending order.
Functional interface Comparator contains default method reversed , which reverses an ex-
isting Comparator 's ordering. When applied to String.CASE_INSENSITIVE_ORDER , the
String s are sorted in descending order.
17.6 Stream<Employee> Manipulations
The example in Figs. 17.9-17.16 demonstrates various lambda and stream capabilities using
a Stream<Employee> . Class Employee (Fig. 17.9) represents an employee with a first name,
last name, salary and department and provides methods for manipulating these values. In ad-
dition, the class provides a getName method (lines 69-72) that returns the combined first and
last name as a String , and a toString method (lines 75-80) that returns a formatted String
containing the employee's first name, last name, salary and department.
1
// Fig. 17.9: Employee.java
2
// Employee class.
3
public class Employee
4
{
5
private String firstName;
6
private String lastName;
7
private double salary;
8
private String department;
9
10
// constructor
11
public Employee(String firstName, String lastName,
12
double salary, String department)
13
{
14
this .firstName = firstName;
15
this .lastName = lastName;
Fig. 17.9 | Employee class for use in Figs. 17.10-17.16. (Part 1 of 3.)
 
 
 
 
Search WWH ::




Custom Search