Optional FlatMap Validation Pipeline

Chain Optional flatMap and map steps to validate and transform input, failing with a typed exception instead of nested null checks.

JavaData Integrity

Code

snippet
import java.util.Optional;

public class OptionalPipeline {

    record Profile(String email, Integer age) {}

    record ValidatedUser(String email, int age) {}

    static Optional<Profile> lookup(String userId) {
        // 实际实现会查数据库;这里用固定映射演示管道
        return switch (userId) {
            case "u1" -> Optional.of(new Profile("[email protected]", 31));
            case "u2" -> Optional.of(new Profile("not-an-email", 22));
            default -> Optional.empty();
        };
    }

    static Optional<String> validEmail(String raw) {
        return raw != null && raw.contains("@") && raw.contains(".")
                ? Optional.of(raw)
                : Optional.empty();
    }

    static ValidatedUser validate(Profile profile) {
        String email = Optional.ofNullable(profile.email())
                .flatMap(OptionalPipeline::validEmail)
                .orElseThrow(() -> new IllegalArgumentException("invalid email: " + profile.email()));
        int age = Optional.ofNullable(profile.age())
                .filter(a -> a >= 18)
                .orElseThrow(() -> new IllegalArgumentException("underage: " + profile.age()));
        return new ValidatedUser(email, age);
    }

    public static void main(String[] args) {
        for (String id : new String[] {"u1", "u2", "u3"}) {
            try {
                System.out.println(id + " -> " + validate(lookup(id).orElseThrow()));
            } catch (IllegalArgumentException e) {
                System.out.println(id + " rejected: " + e.getMessage());
            }
        }
    }
}

How the snippet works

Optional FlatMap Validation Pipeline is built around the classes OptionalPipeline, Profile and ValidatedUser and the functions lookup, validEmail, validate and main.

Repetition is confined to for (String id : new String[] {"u1", "u2", "u3"}) — the rest of the file is straight-line. The possibly-absent value travels in Optional, so callers cannot ignore the empty case.

Applying it

Entry signature: static Optional<Profile> lookup(String userId)

The sequence validate and lookup lives in main; running the file triggers it.

Statements that matter

case "u1" -> Optional.of(new Profile("[email protected]", 31));
case "u2" -> Optional.of(new Profile("not-an-email", 22));
static Optional<String> validEmail(String raw) {
    return raw != null && raw.contains("@") && raw.contains(".")
            ? Optional.of(raw)
            : Optional.empty();
}

Interactive Tools for This Topic

FAQ

How do you run Optional FlatMap Validation Pipeline?
Just run the file; everything it needs ships with the runtime itself.