A IntStream average() method is a terminal operation that used to describe or compute the arithmetic mean of elements of this stream or an empty optional if it is an empty stream, it is specific case for reduction.
1 OptionalDouble average()
return : It returns an OptionalDouble that includes the arithmetic mean of stream element, or an optional empty, if the stream is empty.
IntStream average() method
1 package com.java;
2
3 import java.util.OptionalDouble;
4 import java.util.stream.IntStream;
5
6 public class Main {
7
8 public static void main(String[] args) {
9
10 IntStream stream1 = IntStream.of(10, 20, 30, -40, 50);
11
12 OptionalDouble mean = stream1.average();
13 System.out.println("The arithmetic mean of stream elements is : ");
14 mean.ifPresent(System.out::println);
15 }
16 }
In the above example, a stream object is created using static method of() by passing an elements. A stream method reverse() called that computes an arithmetic mean of stream elements and returns an OptionalDouble object. A result is validated using optional method ifPresent() and print.
1 The arithmetic mean of stream elements is :
2 14.0
IntStream method average() with intermediate operation
IntStream method average() with intermediate operation
1 package com.java;
2
3 import java.util.OptionalDouble;
4 import java.util.stream.IntStream;
5
6 public class Main {
7
8 public static void main(String[] args) {
9
10 IntStream stream1 = IntStream.of(10, 20, 30, -40, 50, 35);
11
12 OptionalDouble mean = stream1.filter(ele -> ele > 10).average();
13 System.out.println("The arithmetic mean of stream elements is : ");
14 mean.ifPresent(System.out::println);
15 }
16 }
In the above example, a Stream object created with elements and filter() method called by specifying a predicate. It validates whether an element value is greater than 10. It returns a resulting stream object having element value greater than 10 and compute an average() of resulting stream elements and print.
1 The arithmetic mean of stream elements is :
2 33.75
average() method with empty stream
average() method with empty stream
1 package com.java;
2
3 import java.util.OptionalDouble;
4 import java.util.stream.IntStream;
5
6 public class Main {
7
8 public static void main(String[] args) {
9
10 IntStream stream1 = IntStream.of();
11
12 OptionalDouble mean = stream1.average();
13 if(mean.isPresent()) {
14 System.out.println("An arithmetic mean is : " + mean.getAsDouble());
15 } else {
16 System.out.println("A stream is empty !!");
17 }
18 }
19 }
In the above example, a stream object is created using of() without specifying an elements. It creates an empty stream object. A stream method average() called that returns an empty Optional object. A optional object is validated using if statement and print empty stream message.
Related options for your search