Java SE 8 Programmer II | Sorting Employees List in Java | Exam 1Z0-809

Sorting Employees List in Java

Question

Given: public class Emp{ String fName; String lName; public Emp (String fn, String ln){ fName = fn; lName = ln; } public String getfName() { return fName; } public String getlName() { return lName; } } and the code fragment: List<Emp> emp = Arrays.asList ( new Emp ("John", "Smith"), new Emp ("Peter", "Sam"), new Emp ("Thomas", "Wale")); emp.stream() //line n1 .collect(Collectors.toList()); Which code fragment, when inserted at line n1, sorts the employees list in descending order of fName and then ascending order of lName?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

B.

The correct answer is A: .sorted(Comparator.comparing(Emp::getfName).reversed().thenComparing(Emp::getlName)).

This code sorts the emp list first in descending order of fName and then ascending order of lName. Here's an explanation of how the code works:

The sorted method is a stream intermediate operation that returns a sorted view of the stream. It takes a Comparator object as an argument, which is used to sort the elements of the stream. In this case, the Comparator is created using two methods: comparing and thenComparing.

The comparing method creates a Comparator that compares objects based on a specific field or method. In this case, it's using the getfName method to compare the Emp objects by their first names.

The reversed method returns a reversed order Comparator, which reverses the natural order of the elements. In this case, it will sort the Emp objects in descending order of their first names.

The thenComparing method creates a Comparator that compares objects based on a secondary field or method in case the primary field or method returns equal values. In this case, it's using the getlName method to compare the Emp objects by their last names.

So, the entire expression .sorted(Comparator.comparing(Emp::getfName).reversed().thenComparing(Emp::getlName)) sorts the emp list first by descending order of first name using comparing(Emp::getfName).reversed(), and then in ascending order of last name using thenComparing(Emp::getlName).

Option B (sorted(Comparator.comparing(Emp::getfName).thenComparing(Emp::getlName))) sorts the Emp objects in ascending order of their first names and then in ascending order of their last names, but does not sort the fName field in descending order as required.

Option C (map(Emp::getfName).sorted(Comparator.reverseOrder())) sorts the list based on first name in descending order, but it only sorts the list by first name and doesn't take into account the last name.

Option D (map(Emp::getfName).sorted(Comparator.reverseOrder().map(Emp::getlName).reversed())) is incorrect because it sorts only based on first name in descending order and then sorts the last name in reverse order, which is not required.