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.
Code Example:
Optional<Integer> first = numbers.stream()
.findFirst();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."