Last Updated : 06 Dec, 2018
Stream findFirst()returns an Optional (a container object which may or may not contain a non-null value) describing the
firstelement of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned.
Syntax :Optional<T> findFirst() Where, Optional is a container object which may or may not contain a non-null value and T is the type of objects and the function returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty.Exception :
If the element selected is null,
NullPointerExceptionis thrown.
Note :findAny() is a
terminal-short-circuitingoperation of Stream interface. This method returns first element satisfying the intermediate operations.
Example 1 :findFirst() function on Stream of Integers.
Java
// Java code for Stream findFirst()
// which returns an Optional describing
// the first element of this stream, or
// an empty Optional if the stream is empty.
import java.util.*;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating a List of Integers
List<Integer> list = Arrays.asList(3, 5, 7, 9, 11);
// Using Stream findFirst()
Optional<Integer> answer = list.stream().findFirst();
// if the stream is empty, an empty
// Optional is returned.
if (answer.isPresent()) {
System.out.println(answer.get());
}
else {
System.out.println("no value");
}
}
}
Output :
3Example 2 :
findFirst() function on Stream of Strings.
Java
// Java code for Stream findFirst()
// which returns an Optional describing
// the first element of this stream, or
// an empty Optional if the stream is empty.
import java.util.*;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating a List of Strings
List<String> list = Arrays.asList("GeeksforGeeks", "for",
"GeeksQuiz", "GFG");
// Using Stream findFirst()
Optional<String> answer = list.stream().findFirst();
// if the stream is empty, an empty
// Optional is returned.
if (answer.isPresent()) {
System.out.println(answer.get());
}
else {
System.out.println("no value");
}
}
}
Output :
GeeksforGeeks
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4