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
maptransforms the value only if one is present.orElseandorElseGetsupply the fallback.ofNullablebridges APIs that still return null.
Keywords and builtins used here
var
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.
Step 3 of 3 in Methods & lambdas, step 17 of 29 in Language basics.