QuestionQ37

Working with Streams and Lambda expressions

Given this code fragment:

List<Integer> listOfNumbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);  

Which code fragment returns a different value?

  • 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);
Explanation

For addition, the identity required by Stream.reduce(identity, accumulator) is 0, because combining 0 with any value must return that value. A parallel reduction may apply the identity independently to multiple partitions. Using 5 as the identity therefore adds it more than once, so the parallel reduction returns a different value. Oracle Java Stream API

Learn more

Community Discussion

No comments yet. Be the first to start the discussion!