Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Stream.findFirst()

Returns the first stream element as an `Optional`.

Available since: Java 8

Syntax

Optional<T> findFirst()
Optional<T> findAny()

Return value

Optional<T>The first element, or an empty `Optional` if the stream is empty.

Examples

The first matching element:

void main() {
    List<String> emails = List.of("anna@mail.com", "oleg@work.org", "ivan@work.org");
    Optional<String> work = emails.stream().filter(e -> e.endsWith("work.org")).findFirst();
    IO.println(work.get());
    IO.println(emails.stream().filter(e -> e.endsWith(".net")).findFirst().orElse("not found"));
}

Output:

oleg@work.org
not found

Notes

It usually follows filter() and works as a search: the stream stops at the first element found. The result is an Optional, so a missing value is handled with orElse(), ifPresent() and similar methods. findAny() may return any matching element in a parallel stream.

See also

  • Stream.filter() — Keeps only the stream elements that match a condition.
  • Stream.anyMatch() — Checks whether at least one element matches a condition.
  • Optional — A container that either holds a value or is empty — a replacement for returning `null`.
  • Optional.orElse() — Returns the value, or a fallback if there is none.

Related recipes

In the tutorial

  • Stream operations — The main Stream API operations — filter, map, sorted, distinct, limit, skip, count, reduce, anyMatch, findFirst and numeric streams.

Thanks for reading!

Donate to the site — we work hard for you.