DoubleStream average() method in Java

Java 8Object Oriented ProgrammingProgramming

The average() method of the DoubleStream class in Java returns an OptionalDouble which is the arithmetic mean of elements of this stream. If the stream is empty, empty is returned.

The syntax is as follows:

OptionalDouble average()

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

To use the DoubleStream class in Java, import the following package:

import java.util.stream.DoubleStream;

First, create DoubleStream and add some elements:

DoubleStream doubleStream = DoubleStream.of(50.8, 35.7, 49.5,12.7, 89.7, 97.4);

Get the average of the elements of the stream:

OptionalDouble res = doubleStream.average();

The following is an example to implement DoubleStream average() method in Java:

Example

 Live Demo

import java.util.*;
import java.util.stream.DoubleStream;
public class Demo {
   public static void main(String[] args) {
      DoubleStream doubleStream = DoubleStream.of(50.8, 35.7, 49.5,12.7, 89.7, 97.4);
      OptionalDouble res = doubleStream.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...
55.96666666666667

Let us see another example:

Example

 Live Demo

import java.util.*;
import java.util.stream.DoubleStream;
public class Demo {
   public static void main(String[] args) {
      DoubleStream doubleStream = DoubleStream.empty();
      OptionalDouble res = doubleStream.average();
      if (res.isPresent()) {
         System.out.println(res.getAsDouble());
      } else {
         System.out.println("Nothing! Stream is empty!");
      }
   }
}

The following is the output displaying nothing since the stream is empty:

Output

Nothing! Stream is empty!
raja
Published on 02-Apr-2019 12:33:50
Advertisements