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.
Loading...
Related Quiz
- In a class instance, synchronized blocks can be used to avoid locking the entire method and only lock ________.
- The setLength method, which allows altering the length of the character sequence stored in the object, is a method of ________.
- ReentrantLock belongs to the ______ package in Java.
- The Character class in Java is used to wrap a value of the primitive data type ________.
- Can a constructor return a value in Java?