Java Streams - DoubleStream reduce(DoubleBinaryOperator op) example








DoubleStream reduce(DoubleBinaryOperator op) performs a reduction on the elements of this stream, using an associative accumulation function, and returns an OptionalDouble describing the reduced value, if any.

Syntax

reduce has the following syntax.

OptionalDouble reduce(DoubleBinaryOperator op)

Example

The following example shows how to use reduce.

import java.util.OptionalDouble;
import java.util.stream.DoubleStream;
//from ww w. j av  a2s  .co  m
public class Main {
  public static void main(String[] args) {
    DoubleStream b = DoubleStream.of(1.1, 2.2, 3.3, 4.4, 5.5);

    OptionalDouble d = b.reduce(Double::sum);
    if (d.isPresent()) {
      System.out.println(d.getAsDouble());
    } else {
      System.out.println("no value");
    }
  }
}

The code above generates the following result.