- 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 findFirst() method in Java
The findFirst() method returns an OptionalDouble describing the first element of this stream. It returns an empty OptionalDouble if the stream is empty.
The syntax is as follows
OptionalDouble findFirst()
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 a DoubleStream with some elements
DoubleStream doubleStream = DoubleStream.of(15.6, 30.2, 50.5, 78.9, 80.4, 95.8);
Now, get the first element of this stream using the findFirst() method
OptionalDouble res = doubleStream.findFirst();
The following is an example to implement DoubleStream findFirst() 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(15.6, 30.2, 50.5, 78.9, 80.4, 95.8); OptionalDouble res = doubleStream.findFirst(); System.out.println("The first element of the stream = "); if (res.isPresent()) System.out.println(res.getAsDouble()); else System.out.println("Nothing!"); } }
Output
The first element of the stream = 15.6
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.findFirst(); if (res.isPresent()) System.out.println(res.getAsDouble()); else System.out.println("Nothing! Stream is empty!"); } }
Here is the output displaying the else condition since the stream is empty
Output
Nothing! Stream is empty!
Advertisements