Consider a scenario where you need to sort a list of employees based on their age and then return the first employee’s name. How would you achieve this using Stream API?

  • a. Use the sorted() method to sort the list of employees by age, then use findFirst() to retrieve the first employee's name.
  • b. Create a custom Comparator to sort the employees, then use stream().filter().findFirst() to get the first employee's name.
  • c. Use stream().min(Comparator.comparingInt(Employee::getAge)).get().getName() to directly get the name of the first employee.
  • d. Sort the list using a loop and compare each employee's age, then return the name of the first employee found.
In this scenario, option 'a' is the correct approach using the Stream API. The sorted() method is used to sort employees by age, and findFirst() returns the first employee's name. Option 'b' is a valid approach but less efficient. Option 'c' is concise but may throw exceptions if the list is empty. Option 'd' is inefficient and not recommended with Streams.
Add your answer
Loading...

Leave a comment

Your email address will not be published. Required fields are marked *