GotchaDifficulty: Advanced1 min

Why get() Without a Check Is the null You Replaced

A method returns Optional so that absence cannot be ignored. The caller writes one more character than they would have and ignores it anyway.

java
String name = findByReference(ref).get().name();
text
Exception in thread "main" java.util.NoSuchElementException: No value present

get() returns the value and throws when there is none. Calling it without checking first is exactly as safe as dereferencing a reference without checking for null — a different exception, in the same place, for the same reason.

What the Optional bought, and what get() gave back
Compared onReturning nullReturning Optional, then get()
Signature warns the callerNoYes
Compiler forces a checkNoNo
Failure when absentNullPointerExceptionNoSuchElementException

Reach for map, orElse, orElseGet, ifPresent or orElseThrow with a message. orElseThrow() is the honest spelling when you genuinely believe it cannot be empty, because the name says what will happen if you are wrong.