DoubleStream findFirst() returns an OptionalDouble (a container object which may or may not contain a non-null value) describing the first element of this stream, or an empty OptionalDouble if the stream is empty.
Syntax :
OptionalDouble findFirst()
Parameters :
- OptionalDouble : A container object which may or may not contain a non-null value.
Return Value : The function returns an OptionalDouble describing the first element of this stream, or an empty OptionalDouble if the stream is empty.
Note : findFirst() is a terminal-short-circuiting operation of Stream interface. This method returns any first element satisfying the intermediate operations.
Example 1 : findFirst() method on Double Stream.
// Java code for DoubleStream findFirst() // which returns an OptionalDouble describing // first element of the stream, or an // empty OptionalDouble if the stream is empty. import java.util.*;
import java.util.stream.DoubleStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating an DoubleStream
DoubleStream stream = DoubleStream.of( 6.2 , 7.3 , 8.4 , 9.5 );
// Using DoubleStream findFirst() to return
// an OptionalDouble describing first element
// of the stream
OptionalDouble answer = stream.findFirst();
// if the stream is empty, an empty
// OptionalDouble is returned.
if (answer.isPresent())
System.out.println(answer.getAsDouble());
else
System.out.println( "no value" );
}
} |
Output :
6.2
Note : If the stream has no encounter order, then any element may be returned.
Example 2 : findFirst() method to return the first element which is divisible by 4.
// Java code for DoubleStream findFirst() // which returns an OptionalDouble describing // first element of the stream, or an // empty OptionalDouble if the stream is empty. import java.util.OptionalDouble;
import java.util.stream.DoubleStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating an DoubleStream
DoubleStream stream = DoubleStream.of( 4.7 , 4.5 ,
8.0 , 10.2 , 12.0 , 16.0 ).parallel();
// Using DoubleStream findFirst().
// Executing the source code multiple times
// must return the same result.
// Every time you will get the same
// Double value which is divisible by 4.
stream = stream.filter(num -> num % 4.0 == 0 );
OptionalDouble answer = stream.findFirst();
if (answer.isPresent())
System.out.println(answer.getAsDouble());
}
} |
Output :
8.0