LongStream average() method in Java

Java 8Object Oriented ProgrammingProgramming

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

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 LongStream class in Java, import the following package.

import java.util.stream.LongStream;

Create LongStream and add elements.

LongStream longStream = LongStream.of(100L, 150L, 180L, 200L, 250L, 300L, 500L);

Get the average of the elements in the stream.

OptionalDouble res = longStream.average();

The following is an example to implement LongStream average() method in Java.

Example

 Live Demo

import java.util.*;
import java.util.stream.LongStream;
public class Demo {
   public static void main(String[] args) {
      LongStream longStream = LongStream.of(100L, 150L, 180L, 200L, 250L, 300L, 500L);
      OptionalDouble res = longStream.average();
      System.out.println("Average...");
      if (res.isPresent()) {
         System.out.println(res.getAsDouble());
      } else {
         System.out.println("Nothing!");
      }
   }
}

Output

Average...
240.0
raja
Published on 27-Mar-2019 11:08:47
Advertisements