IntStream average() method in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 27-Mar-2019 08:41:27
Advertisements