Oracle Certified Professional Java Se 11 Developer · Free Practice Question Hard
Question 72
Question ID: UKOCP20637
Given code:
- package com.udayankhattry.ocp;
- import java.util.Comparator;
- import java.util.List;
- public class Test {
- public static void main(String[] args) {
- var list = List.of(10, 20, 8);
- System.out.println(list.stream().max(Comparator.comparing(a -> a)).get()); //Line 1
- System.out.println(list.stream().max(Integer::compareTo).get()); //Line 2
- System.out.println(list.stream().max(Integer::max).get()); //Line 3
- }
- }
Which of the following statement is true?
- A Line 1, Line 2 and Line 3 print same output
- B Line 1 and Line 2 print same output
- C Line 1 and Line 3 print same output
- D Line 2 and Line 3 print same output
Reveal correct answer
Correct answer: B
Explanation
UKOCP20637:
Variable 'list' infers to List<Integer> type.
In Comparator.comparing(a -> a), keyExtractor is not doing anything special, it just implements Comparator to sort integers in ascending order.
Integer::compareTo is a method reference syntax for the Comparator to sort integers in ascending order.
NOTE: Comparator implementations must return following:
-1 (if 1st argument is less than 2nd argument),
0 (if both arguments are equal) and
1 (if 1st argument is greater than 2nd argument).
Integer::max accepts 2 arguments and returns int value but in this case as all the 3 elements are positive, so value will always be positive.
Line 3 will print different output as it will not sort the list properly.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
