Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Medium
Question 24
Given code of Test.java file:
- package com.udayan.ocp;
- import java.util.stream.IntStream;
- public class Test {
- public static void main(String[] args) {
- int sum = IntStream.rangeClosed(1,3).map(i -> i * i)
- .map(i -> i * i).sum();
- System.out.println(sum);
- }
- }
What will be the result of compiling and executing Test class?
- A 14
- B 6
- C None of the other options
- D 98
Reveal correct answer
Correct answer: D
Explanation
IntStream.rangeClosed(int start, int end) => Returns a sequential stream from start to end, both inclusive and with a step of 1.
IntStream.map(IntUnaryOperator) => Returns a stream consisting of the results of applying the given function to the elements of this stream.
IntStream.rangeClosed(1,3) => [1,2,3].
map(i -> i * i) => [1,4,9].
map(i -> i * i) => [1,16,81].
sum() => 1+16+81 = 98.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
You must be logged in to post a comment.
