LongStream average() in Java with Examples
Last Updated :
14 Sep, 2021
java.util.stream.LongStream in Java 8, deals with primitive Longs. It helps to solve the old problems like finding maximum value in array, finding minimum value in array, sum of all elements in array, and average of all values in array in a new way. LongStream average() returns an OptionalDouble describing the arithmetic mean of elements of this stream, or an empty optional if this stream is empty.
Syntax :
OptionalDouble average()
Where, OptionalDouble is a container object
which may or may not contain a double value.
Below given are some examples to understand the function in a better way.
Example 1 :
Java
import java.util.*;
import java.util.stream.LongStream;
class GFG {
public static void main(String[] args)
{
LongStream stream = LongStream.of(2L, 3L, 4L,
5L, 6L, 7L, 8L);
OptionalDouble obj = stream.average();
if (obj.isPresent()) {
System.out.println(obj.getAsDouble());
}
else {
System.out.println( "-1" );
}
}
}
|
Example 2 :
Java
import java.util.*;
import java.util.stream.LongStream;
class GFG {
public static void main(String[] args)
{
LongStream stream = LongStream.of(2L, 3L, 3L, 4L, 6L, 8L, 8L);
OptionalDouble obj = stream.average();
if (obj.isPresent()) {
System.out.println(obj.getAsDouble());
}
else {
System.out.println( "-1" );
}
}
}
|
Output:
4.857142857142857
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...