Java Streams - IntStream reduce(IntBinaryOperator op) example








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

Syntax

reduce has the following syntax.

OptionalInt reduce(IntBinaryOperator op)

Example

The following example shows how to use reduce.

import java.util.OptionalInt;
import java.util.stream.IntStream;
//from  w w w.j  a va 2 s  .  c  om
public class Main {
  public static void main(String[] args) {
    IntStream i = IntStream.of(6,5,7,1, 2, 3, 3);
    OptionalInt v = i.reduce(Integer::sum);
    if(v.isPresent()){
      System.out.println(v.getAsInt());  
    }else{
      System.out.println(v);
    }
    
  }
}

The code above generates the following result.