Java SE 8 Programmer II — Question 158
Given the code fragment:
List<Integer> nums = Arrays.asList (10, 20, 8):
System.out.println (
//line n1
);
Which code fragment must be inserted at line n1 to enable the code to print the maximum number in the nums list?
Answer options
- A. nums.stream().max(Comparator.comparing(a -> a)).get()
- B. nums.stream().max(Integer : : max).get()
- C. nums.stream().max()
- D. nums.stream().map(a -> a).max()
Correct answer: A
Explanation
The correct answer, A, uses a stream to find the maximum value by comparing elements directly. Option B is incorrect because the syntax for the Comparator is not valid. Option C does not specify a comparator, which may lead to an error if the list is empty. Option D also lacks a comparator for finding the maximum value.