![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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
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
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
Advertisements