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.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- How do you run Optional FlatMap Validation Pipeline?
- Just run the file; everything it needs ships with the runtime itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.