Type the safe Optional alternative to get()
Type the safe Optional alternative to get()
Answer
String name = opt.orElse("anonymous");
orElse returns the value if present, otherwise the fallback. It never throws. Use orElseGet(() -> expensive()) when the fallback is costly — the lambda is only called when the Optional is empty.