- 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
LongStream average() method in Java
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
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
Advertisements