Lesson 4 / 38
Optional
Model a possibly-absent result with Optional as a return type, consume it with map, filter and orElseThrow, and avoid get() and Optional fields.
Use it as a return type
Return Optional<T> from lookups that may find nothing. Consume it with map, filter, orElse, orElseThrow, ifPresent — not get(). Don't use Optional for fields or method parameters.
String city = repo.findUser(id)
.map(User::address)
.map(Address::city)
.orElse("unknown");of vs ofNullable, orElse vs orElseGet
Optional.of(x) throws if x is null; Optional.ofNullable(x) allows null. orElse(expensive()) always evaluates its argument even when the value is present — use orElseGet(() -> expensive()) for lazy fallback computation.
// Bad: buildDefault() runs even when user is present
User u = repo.find(id).orElse(buildDefault());
// Good: buildDefault() runs only when needed
User u2 = repo.find(id).orElseGet(this::buildDefault);