~/ learn/ java-from-zero/ cards/ Gotcha roundup III — APIs
1 of 4

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.

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/bf4a596f-f0da-4a21-bcba-f2e1f61f1721/flashcard utf-8 LF