Course contentsShow
← Java
Lesson 1807 of 2,87037. Optional for Null SafetyFree lesson

Optional.filter: Conditional Presence

Learn how filter tests a condition on a present value, returning empty if the predicate fails or the Optional is empty.

Optional.filter: Conditional Presence

What you'll learn: How to use filter() to keep a value only if it satisfies a condition, converting failures into emptiness.

The Problem of Conditional Values

Sometimes you have a value wrapped in an Optional, but you only care about it if it meets certain criteria. You could use isPresent(), get(), and an if statement—but that's exactly the verbose pattern Optional is meant to eliminate.

What filter() Does

The filter() method tests a present value against a Predicate. If the Optional is empty or the predicate returns false, filter() returns Optional.empty(). If the Optional contains a value and the predicate returns true, it returns the Optional unchanged.

Signature:

Optional<T> filter(Predicate<? super T> predicate)

Think of filter() as a gatekeeper: "You may pass only if you meet this condition."

Examples

Optional<String> name = Optional.of("Alice");

// Keep only if length > 3
Optional<String> filtered = name.filter(s -> s.length() > 3);
// Result: Optional["Alice"]

// Keep only if length > 10
Optional<String> tooShort = name.filter(s -> s.length() > 10);
// Result: Optional.empty

// filter on empty Optional stays empty
Optional<String> empty = Optional.empty();
Optional<String> stillEmpty = empty.filter(s -> s.length() > 3);
// Result: Optional.empty

Chaining with Other Operations

filter() shines when chained with map, flatMap, or terminal methods:

Optional<Integer> age = Optional.of(25);

age.filter(a -> a >= 18)
   .ifPresent(a -> System.out.println("Adult: " + a));
// Prints: Adult: 25

Key Takeaway: filter() applies a condition to a present value, returning the same Optional if the predicate passes or Optional.empty() if it fails or was already empty—enabling concise, fluent conditional logic.