Close

Java 8 Streams - LongStream.average Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.LongStream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamjava.util.stream.LongStreamLongStreamLogicBig

Method:

OptionalDouble average()

This terminal operation returns an OptionalDouble describing the arithmetic mean of elements of this stream, or an empty optional if this stream is empty. This is a special case of reduction.

Examples


Using LongStream#average method:

package com.logicbig.example;

import java.util.stream.LongStream;

public class AverageExample {
public static void main (String[] args) {
double v = LongStream.range(1, 10).average().orElse(-1);
System.out.println(v);
}
}

Output

5.0
Original Post




package com.logicbig.example.longstream;

import java.util.OptionalDouble;
import java.util.stream.LongStream;

public class AverageExample {

public static void main(String... args) {
LongStream stream = LongStream.of(3, 6, 9);
OptionalDouble average = stream.average();
double v = average.orElseGet(() -> -1d);
System.out.println(v);
}
}

Output

6.0




See Also