IntStream average() method in Java


The average() method of the IntStream class in Java returns an OptionalDouble describing the arithmetic mean of elements of this stream, or an empty optional if this stream is empty. It gets the average of the elements of the stream.

The syntax is as follows

OptionalDouble average()

Here, OptionalDouble is a container object which may or may not contain a double value.

Create an IntStream with some elements

IntStream intStream = IntStream.of(15, 13, 45, 18, 89, 70, 76, 56);

Now, get the average of the elements of the stream

OptionalDouble res = intStream.average();

The following is an example to implement IntStream average() method in Java. The isPresent() method of the OptionalDouble class returns true if the value is present

Example

 Live Demo

import java.util.*;
import java.util.stream.IntStream;
public class Demo {
   public static void main(String[] args) {
      IntStream intStream = IntStream.of(15, 13, 45, 18, 89, 70, 76, 56);
      OptionalDouble res = intStream.average();
      System.out.println("Average of the elements of the stream...");
      if (res.isPresent()) {
         System.out.println(res.getAsDouble());
      } else {
         System.out.println("Nothing!");
      }
   }
}

Output

Average of the elements of the stream...
47.75

Updated on: 30-Jul-2019

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements