LongStream average() example

Description

LongStream average() returns an OptionalDouble describing the arithmetic mean of elements of this stream, or an empty optional if this stream is empty.

Syntax

average has the following syntax.


OptionalDouble average()

Example

The following example shows how to use average.


import java.util.OptionalDouble;
import java.util.stream.LongStream;
/* w  ww  .  j  a  va 2 s .  com*/
public class Main {
  public static void main(String[] args) {
    LongStream b = LongStream.of(1L, 2L, Long.MAX_VALUE, Long.MIN_VALUE);
    OptionalDouble o = b.average();
    
    if(o.isPresent()){
      System.out.println(o.getAsDouble()); 
    }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