1Z0-809 · Question #116
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…
The correct answer is A. nums.stream().max(Comparator.comparing(a -> a)).get(). Option A works because Stream.max() requires a Comparator argument, and Comparator.comparing(a -> a) creates a valid natural-order comparator by using the identity function as the key extractor - it compares each Integer by its own value, correctly returning Optional<Integer>…
Question
Options
- Anums.stream().max(Comparator.comparing(a -> a)).get()
- Bnums.stream().max(Integer :: max).get()
- Cnums.stream().max()
- Dnums.stream().map(a -> a).max()
How the community answered
(25 responses)- A84% (21)
- B4% (1)
- C8% (2)
- D4% (1)
Explanation
Option A works because Stream.max() requires a Comparator argument, and Comparator.comparing(a -> a) creates a valid natural-order comparator by using the identity function as the key extractor - it compares each Integer by its own value, correctly returning Optional<Integer> which .get() unwraps to 20.
Option B compiles but violates the Comparator contract: Integer::max(a, b) always returns the larger value (always positive), so it never returns a negative number - meaning the comparator can never signal "less than," making the result unreliable.
Options C and D both fail to compile: Stream.max() has no zero-argument overload, so calling .max() without a Comparator is a compilation error regardless of what precedes it.
Memory tip: max() on a stream is not like Math.max() - it can't compare on its own and always needs a Comparator. When in doubt, reach for Comparator.comparing(...) or Comparator.naturalOrder() as safe, readable choices.
Community Discussion
No community discussion yet for this question.