The Stream.findFirst() method in Java returns an Optional describing the first element of the stream. If the stream is empty, it returns an empty Optional. This is a terminal and short-circuiting operation, meaning it stops processing as soon as the first element is found. If the stream has no defined encounter order any element may be returned.
Example:
import java.util.*;
class GFG {
public static void main(String[] args) {
List<String> list = Arrays.asList("Java", "Stream", "API");
Optional<String> result = list.stream().findFirst();
System.out.println(result.get());
}
}
Explanation:
- list.stream() converts the list into a stream.
- findFirst() retrieves the first element of the stream and returns it as an Optional.
- result.get() extracts and prints the value stored inside the Optional.
- Since the stream is not empty, the first element "Java" is printed.
Syntax:
Optional<T> findFirst()
- Parameters: This method does not take any parameters.
- Return Value: Returns an Optional<T> containing the first element of the stream and returns an empty Optional if the stream is empty.
Example 1: This code demonstrates using Stream.findFirst() to retrieve the first element of a stream, returning an Optional to safely handle empty streams.
import java.util.*;
class GFG {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(3, 5, 7, 9, 11);
Optional<Integer> answer = list.stream().findFirst();
if (answer.isPresent()) {
System.out.println(answer.get());
} else {
System.out.println("no value");
}
}
}
Output
3
Explanation:
- findFirst() returns the first element of the stream wrapped in an Optional.
- isPresent() checks whether a value exists inside the Optional.
- If a value is present, get() prints the first element (3); otherwise, "no value" is printed.
Example 2: This code demonstrates the use of Stream.findFirst() in Java to retrieve the first element from a stream in a safe way using Optional.
import java.util.*;
class GFG {
public static void main(String[] args) {
List<String> list = Arrays.asList(
"GeeksforGeeks", "for", "GeeksQuiz", "GFG"
);
Optional<String> answer = list.stream().findFirst();
if (answer.isPresent()) {
System.out.println(answer.get());
} else {
System.out.println("no value");
}
}
}
Output
GeeksforGeeks
Explanation:
- The list is converted into a stream, and findFirst() is called to get the first element.
- findFirst() returns an Optional<String> to handle cases where the stream might be empty.