Friday, November 14, 2025
HomeLanguagesJavaIntStream average() in Java with Examples

IntStream average() in Java with Examples

java.util.stream.IntStream in Java 8, deals with primitive ints. 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. IntStream 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




// Java code for IntStream average()
import java.util.*;
import java.util.stream.IntStream;
 
class GFG {
 
    // Driver code
    public static void main(String[] args)
    {
 
        // creating a stream
        IntStream stream = IntStream.of(2, 3, 4, 5, 6, 7, 8);
 
        // OptionalDouble is a container object
        // which may or may not contain a
        // double 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");
        }
    }
}


Output : 

5.0

Example 2 :  

Java




// Implementation of IntStream average()
import java.util.*;
import java.util.stream.IntStream;
 
class GFG {
 
    // Driver code
    public static void main(String[] args)
    {
 
        // creating a stream
        IntStream stream = IntStream.of(2, 3, 3, 4, 6, 8, 8);
 
        // OptionalDouble is a container object
        // which may or may not contain a
        // double 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");
        }
    }
}


Output : 

4.857142857142857

 

RELATED ARTICLES

Most Popular

Dominic
32399 POSTS0 COMMENTS
Milvus
95 POSTS0 COMMENTS
Nango Kala
6765 POSTS0 COMMENTS
Nicole Veronica
11917 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11984 POSTS0 COMMENTS
Shaida Kate Naidoo
6889 POSTS0 COMMENTS
Ted Musemwa
7142 POSTS0 COMMENTS
Thapelo Manthata
6837 POSTS0 COMMENTS
Umr Jansen
6840 POSTS0 COMMENTS