Java Streams - LongStream reduce(LongBinaryOperator op) example








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

Syntax

reduce has the following syntax.

OptionalLong reduce(LongBinaryOperator op)

Example

The following example shows how to use reduce.

import java.util.OptionalLong;
import java.util.stream.LongStream;
/* w w  w. j  a v a2s.co m*/
public class Main {
  public static void main(String[] args) {
    LongStream b = LongStream.of(1L, 2L, 3L, 4L);
    
    OptionalLong v = b.reduce(Long::sum);
    if(v.isPresent()){
      System.out.println(v.getAsLong());
    }else{
      System.out.println("no value");  
    }
    
  }
}

The code above generates the following result.