Java Streams - Stream reduce(U identity, BiFunction accumulator, BinaryOperator combiner) example








Stream reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner) performs a reduction on the elements of this stream, using the provided identity, accumulation and combining functions.

Syntax

reduce has the following syntax.

<U> U reduce(U identity,  BiFunction<U,? super T,U> accumulator,  BinaryOperator<U> combiner)

Example

The following example shows how to use reduce.

import java.util.Arrays;
import java.util.List;
/*from w  w w.  j a  v a2s  .  c  om*/
public class Main {
  public static void main(String[] args) {
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

    double sum = numbers
        .parallelStream()
        .reduce(0.0, (partialSum, a) -> partialSum + a, Double::sum);
       System.out.println(sum);

  }
}

The code above generates the following result.