Topic: Programming in Java
What is the value of result?
import java.util.stream.Stream;
public class Test {
public static void main(String []args)
{
int result = Stream.of(1, 2, 3, 4) .reduce(20, (a, b) -> a + b, (a,b) -> a*b);
System.out.println(result);
}
}
- A. 20
- B. 40
- C. 30
- D. 50
Answer: C. 30
Explanation: The `reduce` method takes an identity value (20), an accumulator function (addition), and a combiner function (multiplication). Because this is a sequential stream (not a parallel stream), the combiner is never invoked. The accumulator simply adds each element to the accumulated total sequentially: 20 + 1 = 21, 21 + 2 = 23, 23 + 3 = 26, 26 + 4 = 30.