Optional for Null Safety

Demonstrates using Optional to handle potentially absent values safely, with map, flatMap, filter, orElse, and ifPresent operations to avoid NullPointerExcep...

JavaResilience

Code

javasnippet
42 lines
import java.util.Optional;
import java.util.List;

public class OptionalHandling {

    record User(String name, String email) {}

    static Optional<User> findUser(List<User> users, String name) {
        return users.stream()
            .filter(u -> u.name().equals(name))
            .findFirst();
    }

    public static void main(String[] args) {
        List<User> users = List.of(
            new User("Alice", "alice@example.com"),
            new User("Bob", "bob@example.com")
        );

        String email = findUser(users, "Alice")
            .map(User::email)
            .orElse("not found");
        System.out.println("Alice's email: " + email);

        findUser(users, "Charlie")
            .ifPresentOrElse(
                u -> System.out.println("Found: " + u),
                () -> System.out.println("Charlie not found")
            );

        String upperEmail = findUser(users, "Bob")
            .map(User::email)
            .filter(e -> e.endsWith(".com"))
            .map(String::toUpperCase)
            .orElseThrow(() -> new RuntimeException("Invalid email"));
        System.out.println("Bob's email (upper): " + upperEmail);

        Optional<String> combined = findUser(users, "Alice")
            .flatMap(u -> Optional.ofNullable(u.email()));
        System.out.println("FlatMapped: " + combined);
    }
}

How the snippet works

Under the hood: the classes OptionalHandling and User and the functions findUser and main.

The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable. Absence is modeled with Optional — the type system reminds you to check before unwrapping.

Applying it

The main signature reads static Optional<User> findUser(List<User> users, String name)

The demo output is labeled (Alice's email:, Found:, Charlie not found), so every printed line maps back to its originating operation.

Execute the file and main walks through findUser, in that order.

Statements that matter

return users.stream()
    .filter(u -> u.name().equals(name))
    .findFirst();
.flatMap(u -> Optional.ofNullable(u.email()));
.filter(e -> e.endsWith(".com"))
.map(String::toUpperCase)
.orElseThrow(() -> new RuntimeException("Invalid email"));

Interactive Tools for This Topic

FAQ

What does Optional for Null Safety print when run?
The script runs standalone; its 5 labeled outputs include `Alice's email:`, `Found:`, `Charlie not found`.