Optional Map And FlatMap Chaining

Transform wrapped values with map and keep the Optional flat with flatMap, so parsing and validation steps compose without nested wrappers.

JavaForm Validation

Code

snippet
import java.util.Optional;

public class LookupChain {

    static Optional<Integer> parsePort(String raw) {
        try {
            return Optional.of(Integer.parseInt(raw));
        } catch (NumberFormatException e) {
            return Optional.empty();
        }
    }

    public static void main(String[] args) {
        // map:包装值存在时做一次转换,结果仍留在 Optional 里
        Optional<String> raw = Optional.of(" 8080 ");
        Optional<Integer> port = raw.map(String::strip).map(Integer::parseInt);
        System.out.println("mapped: " + port);

        // flatMap:mapper 自己返回 Optional,不会出现 Optional<Optional<T>>
        Optional<Integer> parsed = parsePort("99999"); // 合法 int,但超出端口范围
        Optional<Integer> validated = parsed.flatMap(p -> p > 0 && p <= 65535
                ? Optional.of(p)
                : Optional.<Integer>empty());
        System.out.println("validated: " + validated);

        // 两种调用串联:任何一环为 empty,后续步骤全部跳过
        Optional<Integer> broken = Optional.<String>empty()
                .map(String::strip)
                .map(Integer::parseInt)
                .flatMap(p -> Optional.of(p * 2));
        System.out.println("empty chain: " + broken);
    }
}

The narrative inside the file

The snippet is organized around the class LookupChain and the functions parsePort and main.

Optional wraps the possibly-absent value instead of a null sentinel.

Watch out for

  • Zero packages pulled in — the runtime ships every API this code touches.

Putting it to use

Entry signature: static Optional<Integer> parsePort(String raw)

The file’s steps show up in the output as mapped:, validated:, empty chain:.

Running the file executes main, which drives parsePort in order.

Core lines

Optional<Integer> port = raw.map(String::strip).map(Integer::parseInt);
return Optional.of(Integer.parseInt(raw));
return Optional.empty();

Interactive Tools for This Topic

FAQ

What does Optional Map And FlatMap Chaining print when run?
Execute the whole file; each printed line is prefixed with a label like `mapped:`, `validated:`, `empty chain:`.