Given the class definition:
class Employee {/* w ww .j av a2 s . c o m*/ String firstName; String lastName; public Employee(String fName, String lName) { firstName = fName; lastName = lName; } public String toString() { return firstName + " " + lastName; } String getFirstName() { return firstName; } String getLastName() { return lastName; } }
here is a code segment:
Employee[] employees = { new Employee("Dan", "Abrams"), new Employee("Web", "SQL"), new Employee("John", "SQL"), new Employee("Dan", "Java"), new Employee("Web", "Java") };/*from w w w .j a va2 s .c o m*/ Comparator<Employee> sortByFirstName = ((e1, e2) -> e1.getFirstName().compareTo(e2.getFirstName())); Comparator<Employee> sortByLastName = ((e1, e2) -> e1.getLastName().compareTo(e2.getLastName())); // SORT
the sorting needs to be performed in descending order of the first names; when first names are the same, the names should then be sorted in ascending order of the last names.
For that, which one of the following code segment will you replace for the line marked by the comment SORT?.
a) Stream.of(employees)//from w ww .ja v a 2 s . co m .sorted(sortByFirstName.thenComparing(sortByLastName)) .forEach(System.out::println); b) Stream.of(employees) .sorted(sortByFirstName.reversed().thenComparing(sortByLastName)) .forEach(System.out::println); c) Stream.of(employees) .sorted(sortByFirstName.thenComparing(sortByLastName).reversed()) .forEach(System.out::println); d) Stream.of(employees) .sorted(sortByFirstName.reversed().thenComparing(sortByLastName).reversed()) .forEach(System.out::println);
b)
the sortByFirstName()
is a Comparator that sorts names by the Employee's first name.
Because we need to sort the names in descending order, we need to call the reversed()
method.
after that, we need to sort the last names in ascending order, and hence we can call thenComparing(sortByLastName)
.