findFirst() is a short-circuiting terminal Stream operation that returns the first element of the stream in encounter order, wrapped in an Optional.
Key Points
findFirst() stops processing as soon as it retrieves the first element, making it efficient even on large streams.
The Optional<T> return type handles the case of an empty stream without needing a null check.
Unlike findAny(), findFirst() guarantees the element returned respects the stream's encounter order, even in parallel execution.
It's commonly paired with filter() to retrieve the first element matching a specific condition.
Because it enforces ordering, findFirst() can be slightly less efficient than findAny() on parallel streams.
Example
Given the list [7, 3, 9, 1], calling findFirst() returns an Optional containing 7, the first element in the stream's order.
Optional<Integer> first = numbers.stream()
.findFirst();
Common Mistakes
Calling get() on the Optional without checking it: an empty stream makes get() throw NoSuchElementException. Use orElse(), orElseThrow() or ifPresent() instead.
Expecting findFirst() to be fast on a parallel stream: it must respect encounter order, so it can be slower than findAny() there.
Forgetting that findFirst() throws NullPointerException if the first element is null, because Optional cannot hold null.
Follow-up Questions
What is the difference between findFirst() and findAny()? findFirst() always returns the first element in encounter order; findAny() may return any element and is cheaper on parallel streams.
Is findFirst() a short-circuiting operation? Yes. It stops as soon as it finds one element, so it works even on infinite streams after a filter().
Interview Tip
A concise interview answer is
findFirst() returns the first element of the stream in encounter order, wrapped in an Optional to safely handle an empty stream. Unlike findAny(), it guarantees ordering even on parallel streams, which can make it marginally slower but more predictable.