Java SE 17 Developer — Question 40
Given the code fragment:
List<Integer> listOfNumbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Which code fragment returns different values?
Answer options
- A. int sum = listOfNumbers.stream().reduce(0, Integer::sum) + 5;
- B. int sum = listOfNumbers.parallelStream().reduce(0, Integer::sum) + 5 ;
- C. int sum = listOfNumbers.parallelStream().reduce((m, n) -> m + n).orElse(5) + 5;
- D. int sum = listOfNumbers.parallelStream().reduce(5, Integer::sum);
- E. int sum = listOfNumbers.stream().reduce(5, (a, b) -> a+ b);
Correct answer: D
Explanation
The correct answer is D because it initializes the reduction with 5, which changes the final sum compared to the others that start with 0 or use a different approach. Options A, B, C, and E all start their reduction with 0 or compute the sum in a way that includes the elements of the list directly without altering the initial value to 5.