Given the code fragment:
List
Which code fragment returns different values?
Given the code fragment:
List
Which code fragment returns different values?
The code fragment that returns different values is: int sum = listOfNumbers.parallelStream().reduce(5, Integer::sum);. This is because the reduce operation with a parallel stream uses the given identity value (5 in this case) as the initial value for each partition of the stream. Consequently, each element of the list will be summed with 5 independently in parallel, resulting in a different final total compared to using a standard stream or other parallel stream reductions with different identities or reduction methods.
D tested correct
D is correct answer
// D. We need to be careful while using parallelStream()
// D. int sum = listOfNumbers.parallelStream().reduce(5, Integer::sum); // (1 + 5) + (2 + 5) + (3 + 5) + (4 + 5) + (5 + 5) + (6 + 5) + (7 + 5) + (8 + 5) + (9 + 5) + (10 + 5) = 105 System.out.println(">>> sum = " + sum); // >>> sum = 105 A, B, C, E return sum = 60.