IntStream findFirst() in Java
Last Updated :
06 Dec, 2018
IntStream findFirst() returns an OptionalInt (a container object which may or may not contain a non-null value) describing the first element of this stream, or an empty OptionalInt if the stream is empty
Syntax :
OptionalInt findFirst()
Where, OptionalInt is a container object which
may or may not contain a non-null value
and the function returns an OptionalInt describing the
first element of this stream, or an empty OptionalInt
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 Integer Stream.
import java.util.*;
import java.util.stream.IntStream;
class GFG {
public static void main(String[] args)
{
IntStream stream = IntStream.of( 6 , 7 , 8 , 9 );
OptionalInt answer = stream.findFirst();
if (answer.isPresent())
System.out.println(answer.getAsInt());
else
System.out.println( "no value" );
}
}
|
Output :
6
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.
import java.util.OptionalInt;
import java.util.stream.IntStream;
class GFG {
public static void main(String[] args)
{
IntStream stream = IntStream.of( 4 , 5 , 8 , 10 , 12 , 16 )
.parallel();
stream = stream.filter(num -> num % 4 == 0 );
OptionalInt answer = stream.findFirst();
if (answer.isPresent())
System.out.println(answer.getAsInt());
}
}
|
Output :
4
Share your thoughts in the comments
Please Login to comment...