LongStream reduce(LongBinaryOperator op) example

Description

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;
//from  w w w . ja  va2s .c o 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.





















Home »
  Java Streams »
    Reference »




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