LongStream average() in Java with Examples
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 code for LongStream average() import java.util.*; import java.util.stream.LongStream; class GFG { // Driver code public static void main(String[] args) { // creating a stream LongStream stream = LongStream.of(2L, 3L, 4L, 5L, 6L, 7L, 8L); // OptionalDouble is a container object // which may or may not contain a // doouble value. OptionalDouble obj = stream.average(); // If a value is present, isPresent() will // return true and getAsDouble() will // return the value if (obj.isPresent()) { System.out.println(obj.getAsDouble()); } else { System.out.println("-1"); } } } |
5.0
Example 2 :
// Implementation of LongStream average() import java.util.*; import java.util.stream.LongStream; class GFG { // Driver code public static void main(String[] args) { // creating a stream LongStream stream = LongStream.of(2L, 3L, 3L, 4L, 6L, 8L, 8L); // OptionalDouble is a container object // which may or may not contain a // doouble value. OptionalDouble obj = stream.average(); // If a value is present, isPresent() will // return true and getAsDouble() will // return the value if (obj.isPresent()) { System.out.println(obj.getAsDouble()); } else { System.out.println("-1"); } } } |
4.857142857142857
Recommended Posts:
- LongStream min() in Java with examples
- LongStream max() in Java with examples
- LongStream distinct() in Java with examples
- LongStream mapToInt() in Java with Examples
- LongStream filter() in Java with examples
- LongStream peek() in Java with examples
- LongStream empty() in Java with examples
- LongStream count() in Java with examples
- LongStream noneMatch() in Java with examples
- LongStream anyMatch() in Java with examples
- LongStream allMatch() in Java with examples
- LongStream reduce(long identity, LongBinaryOperator op) in Java with Examples
- DoubleStream average() in Java with Examples
- IntStream average() in Java with Examples
- LongStream findAny() with examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


