1Z0-819 · Question #61
You want to calculate the average of numbers. numbers = List.of(1,2,3,4,5,6,7,8,9); Which two codes will accomplish this? (Choose two.)
The correct answer is B. B. double avg = numbers.stream().mapToDouble(n -> n).average().getAsDouble(). Option B is correct because it follows the complete, valid chain for computing a primitive average: mapToDouble(n -> n) converts the Stream<Integer> to a DoubleStream, .average() returns an OptionalDouble, and .getAsDouble() unwraps it to a primitive double - all steps compile…
Question
Options
- AA. double avg = numbers.stream().parallel().averagingDouble(n -> n).
- BB. double avg = numbers.stream().mapToDouble(n -> n).average().getAsDouble();
- CC. double avg = numbers.stream().mapToInt(n -> i).average().parallel();
- DD. double avg = numbers.stream().mapToInt(n -> n).average();
- EE. double avg = numbers.stream().collect(Collectors.averaging.Double(n -> n));
How the community answered
(28 responses)- A4% (1)
- B75% (21)
- C14% (4)
- E7% (2)
Explanation
Option B is correct because it follows the complete, valid chain for computing a primitive average: mapToDouble(n -> n) converts the Stream<Integer> to a DoubleStream, .average() returns an OptionalDouble, and .getAsDouble() unwraps it to a primitive double - all steps compile and execute correctly.
Why the distractors fail:
- A -
averagingDouble()is aCollector, not a terminal operation onStream; it must be used ascollect(Collectors.averagingDouble(...)), not chained after.parallel(). - C - The lambda
n -> ireferences an undefined variablei(should ben), andOptionalInthas no.parallel()method, so this doesn't compile. - D -
mapToInt(...).average()returnsOptionalDouble, which cannot be directly assigned todouble avgwithout calling.getAsDouble()- this is a compile error. - E -
Collectors.averaging.Doubleis not valid Java syntax; the correct method isCollectors.averagingDouble(...)(one word, camelCase).
Note: The question says "Choose two," but only B is fully correct as written. This appears to be a flawed question - likely D was intended as a second correct answer with
.getAsDouble()appended, or E with the correctCollectors.averagingDoublesyntax.
Memory tip: For stream averages, think "map → average → unwrap": mapToDouble() → .average() → .getAsDouble(). If you skip the unwrap, you get an Optional, not a double.
Topics
Community Discussion
No community discussion yet for this question.