Java

Optional with Streams

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`Optional::stream` (Java 9+) bridges optionals into the Stream API — collect all the `Some` values from a list of optionals, drop the empties, in one pipeline.
Java
Raw
import java.util.*;
import java.util.stream.*;

class Demo {
    Optional<Integer> parseInt(String s) {
        try { return Optional.of(Integer.parseInt(s)); }
        catch (NumberFormatException e) { return Optional.empty(); }
    }

    void example() {
        var inputs = List.of("1", "two", "3", "four", "5");

        // Old way — filter + get is ugly:
        //   .filter(Optional::isPresent).map(Optional::get)
        //
        // Java 9+ — flatMap with Optional::stream
        List<Integer> nums = inputs.stream()
            .map(this::parseInt)
            .flatMap(Optional::stream)
            .toList();
        System.out.println(nums);                       // [1, 3, 5]

        // First non-empty match
        Optional<Integer> first = inputs.stream()
            .map(this::parseInt)
            .flatMap(Optional::stream)
            .findFirst();
        System.out.println(first);                      // Optional[1]
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.