VOOZH about

URL: https://www.geeksforgeeks.org/java/stream-findfirst-java-examples/

⇱ Stream findFirst() in Java with examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Stream findFirst() in Java with examples

Last Updated : 26 Dec, 2025

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:

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.


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.


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.

Related Topics:

Comment