1Z0-819 · Question #65
Given import java.util.List; import java.util.function.BinaryOperator; public class Main { public static void main(String... args) { List<Employee> list = List.of(new Employee("John", 80000.0), new…
The correct answer is C. double totalSalary = list.stream().mapToDouble(e -> e.getSalary() * ratio).reduce(0.0,bo).orElse(0.0). Option C is correct because mapToDouble() returns a DoubleStream (not Stream<Double>), and DoubleStream's single-argument reduce(DoubleBinaryOperator) returns an OptionalDouble - meaning .orElse(0.0) is required to safely unbox the result into a double, mirroring line 1's…
Question
Options
- Adouble totalSalary = list.stream().map(e -> e.getSalary() * ratio).reduce(bo).ifPresent(p -> p. doubleValue());
- Bdouble totalSalary = list.stream().mapToDouble(e -> e.getSalary() * ratio).sum();
- Cdouble totalSalary = list.stream().mapToDouble(e -> e.getSalary() * ratio).reduce(0.0,bo).orElse(0.0);
- Ddouble totalSalary = list.stream().mapToDouble(e -> e.getSalary() * ratio).reduce(starts, bo);
How the community answered
(27 responses)- A4% (1)
- B11% (3)
- C78% (21)
- D7% (2)
Explanation
Option C is correct because mapToDouble() returns a DoubleStream (not Stream<Double>), and DoubleStream's single-argument reduce(DoubleBinaryOperator) returns an OptionalDouble - meaning .orElse(0.0) is required to safely unbox the result into a double, mirroring line 1's behavior of returning a plain double with a guaranteed identity of 0.0.
Why the distractors fail:
- A -
reduce(bo)onStream<Double>returnsOptional<Double>, andifPresent()returnsvoid, so the assignment todouble totalSalarywon't compile. - B -
.sum()is hardcoded summation that doesn't delegate toboat all; it's numerically equivalent for this input, but "equivalent to line 1" means using the same accumulator contract, not just producing the same number. - D - After
mapToDouble()you're onDoubleStream, which expects aDoubleBinaryOperator, not aBinaryOperator<Double>- a type mismatch that causes a compile error, and there's no.orElse()to handle theOptionalDoublereturn.
Memory tip: When you convert a Stream<Double> to a DoubleStream via mapToDouble(), remember the "primitive stream tax" - reduce without an identity returns OptionalDouble, so you always need .orElse() or .getAsDouble() to land back on a primitive double.
Topics
Community Discussion
No community discussion yet for this question.