typestar

Optional in Java

A container that admits it might be empty.

import java.util.Optional;

Optional<String> found = Optional.of("result.txt");
Optional<String> missing = Optional.empty();

System.out.println(found.map(String::toUpperCase).orElse("none"));
System.out.println(missing.orElse("none"));

// ofNullable bridges APIs that still return null
var legacy = Optional.ofNullable(System.getenv("NO_SUCH_VAR"));
System.out.println(legacy.isPresent());
System.out.println(legacy.orElseGet(() -> "computed fallback"));

How it works

  1. map transforms the value only if one is present.
  2. orElse and orElseGet supply the fallback.
  3. ofNullable bridges APIs that still return null.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
456
Tokens
121
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 85 seconds.

Type this snippet

Step 3 of 3 in Methods & lambdas, step 17 of 29 in Language basics.

← Previous Next →