Course contentsShow
← Java
Lesson 1420 of 2,87032. Streams API: Intermediate OperationsFree lesson

filter Syntax and Predicate Parameter

Explore the syntax of filter, which takes a Predicate<T> and returns a Stream<T> containing only matching elements.

filter Syntax and Predicate Parameter

You'll learn exactly how to use the filter operation's syntax, including what a Predicate<T> is and how to pass one to filter elements from a stream.

The Core Syntax

The filter operation has a simple but powerful signature:

Stream<T> filter(Predicate<T> predicate)

This means filter takes a Predicate<T> as its parameter and returns a new Stream<T> containing only the elements that satisfy the predicate's condition. Remember, a Predicate is a functional interface with a single method: boolean test(T t). It examines each element and returns true if the element should be kept, false if it should be filtered out.

How the Predicate Works

Think of a Predicate as a gatekeeper at a club. Each stream element approaches the gate, and the predicate decides: "You pass" (true) or "Not today" (false). Only elements that pass make it into the resulting stream.

Common Ways to Provide a Predicate

You can pass a predicate to filter in several ways:

Lambda expression:

stream.filter(n -> n > 10)

Method reference:

stream.filter(String::isEmpty)

Predicate variable:

Predicate<Integer> isEven = n -> n % 2 == 0;
stream.filter(isEven)

Type Safety

The generic type T in Predicate<T> must match your stream's element type. If you have a Stream<String>, you provide a Predicate<String>. The compiler ensures your predicate receives the correct type.

Return Value

Crucially, filter returns a new stream, not a collection or a count. It's an intermediate operation, so nothing actually happens until you attach a terminal operation.

Key Takeaway: The filter operation accepts a Predicate<T> that tests each element, returning a new Stream<T> containing only the elements for which the predicate returns true.