Course contentsShow
← Java
Lesson 1547 of 2,87033. Streams API: Terminal OperationsFree lesson

Combining filter with findFirst and findAny

Practice common patterns of filtering streams and then finding the first or any matching element efficiently.

Combining filter with findFirst and findAny

You'll learn how to efficiently chain filtering predicates with find operations to locate the first (or any) matching element in a stream.

The Core Pattern

One of the most common and powerful stream patterns is filtering down to elements that match certain criteria, then immediately finding one result. Instead of collecting all matches, you can short-circuit the operation by combining filter() with findFirst() or findAny().

This pattern answers questions like: "Give me the first user over 18" or "Find any available product in stock."

How It Works

The filter() operation narrows your stream to only elements matching your predicate. When you chain findFirst() or findAny() afterward, the stream stops processing as soon as a match is found—it doesn't needlessly examine remaining elements.

Optional<String> firstLongName = names.stream()
    .filter(name -> name.length() > 5)
    .findFirst();

Optional<Integer> anyEvenNumber = numbers.stream()
    .filter(n -> n % 2 == 0)
    .findAny();

Why This Combination Is Powerful

Think of it like searching through a deck of cards: you shuffle through (filter) looking only at red cards, and stop the moment you find one (findFirst). You don't keep flipping through the entire deck.

The efficiency comes from short-circuiting: the stream only processes elements until it finds one that passes the filter. This is especially valuable with large or expensive-to-compute streams.

Sequential vs Parallel Choice

Use findFirst() when order matters. Use findAny() in parallel streams when any match will do—it allows the stream to return whichever thread finds a match first, maximizing parallel performance.

Key Takeaway: Combining filter() with findFirst() or findAny() creates an efficient, short-circuiting pattern for locating a single matching element without processing the entire stream.