5.2.  Implement decomposition and reduction in streams

  • blah


The reduce(T identity, BinaryOperator<T> accumulator) method of the Stream interface performs a reduction operation on the stream to reduce the stream to a single value. It takes an initial value and an accumulator that is a BinaryOperator<T> as arguments. The first time, the accumulator receives the initial value and the first element of the stream as arguments, and returns a value. The second time, the accumulator receives the value returned from its previous call and the second element from the stream. This process continues until all elements of the stream have been passed to the accumulator.

The returned value from the last call of the accumulator is returned from the reduce(...) method. The following snippet of code performs the summation of all integers in the stream:

Integer[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
List<Integer> list = new ArrayList<>(Arrays.asList(arr));
Integer sum = list.stream().reduce(0, (n1, n2) -> n1 + n2); // must be 36
System.out.print("Sum of all integers in the stream : " + sum);


The Integer class contains a static sum(...) method to perform sum of two integers. You can rewrite the code using a method reference, like so:

Integer sum = list.stream().reduce(0, Integer::sum);

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Exam 1Z0-810: Upgrade to Java SE 8 Programmer Quiz