- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
DoubleStream average() method in Java
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
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
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!
Advertisements