Stream reduce(T identity, BinaryOperator accumulator) example

Description

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. ja  v  a 2s.  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.





















Home »
  Java Streams »
    Reference »




Collectors
DoubleStream
DoubleStream.Builder
IntStream
IntStream.Builder
LongStream
LongStream.Builder
Stream
Stream.Builder