Java Streams - Stream reduce(T identity, BinaryOperator accumulator) example








Stream reduce(T identity, BinaryOperator<T> accumulator) performs a reduction on the elements of this stream, using the provided identity value and an associative accumulation function, and returns the reduced value.

Syntax

reduce has the following syntax.

T reduce(T identity, BinaryOperator<T> accumulator)

Example

The following example shows how to use reduce.

import java.util.Arrays;
import java.util.List;
/*from  w  w  w . j a  v a 2 s  . c  o m*/
public class Main {
  public static void main(String[] args) {
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
    int sum = numbers.stream()
                     .reduce(0, Integer::sum); 
    System.out.println(sum);
  }
}

The code above generates the following result.