nerdexam
Oracle

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…

Working with Streams and Lambda Expressions

Question

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.)

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)
  • A
    4% (1)
  • B
    75% (21)
  • C
    14% (4)
  • E
    7% (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 a Collector, not a terminal operation on Stream; it must be used as collect(Collectors.averagingDouble(...)), not chained after .parallel().
  • C - The lambda n -> i references an undefined variable i (should be n), and OptionalInt has no .parallel() method, so this doesn't compile.
  • D - mapToInt(...).average() returns OptionalDouble, which cannot be directly assigned to double avg without calling .getAsDouble() - this is a compile error.
  • E - Collectors.averaging.Double is not valid Java syntax; the correct method is Collectors.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 correct Collectors.averagingDouble syntax.

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

#Stream Operations#Lambda Expressions#Optional Types#mapToDouble()

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice