Java
Java Optional: Handling Values That May Be Absent
Use Optional to express a lookup that might not find a result.
You are reading a translated version.
Make absence explicit
A lookup can succeed or return no result. Optional makes that possibility visible in the return type.
import java.util.Optional;
public class Main {
static Optional<String> findName(int id) {
return id == 1 ? Optional.of("Nara") : Optional.empty();
}
public static void main(String[] args) {
String name = findName(2).orElse("Pengunjung");
System.out.println(name);
}
}
Choose a fallback
orElse is suitable for a simple fallback value. If producing a fallback is expensive, use orElseGet so that work only happens when the Optional is empty. The original example uses Pengunjung, meaning “Visitor,” as its fallback.
Avoid unchecked get calls
Calling get() on an empty Optional throws an exception. Prefer map, ifPresent, or an appropriate fallback according to the caller's needs.
Exercise
Change the ID to 1 and observe the result. Then add map(String::toUpperCase) before orElse to uppercase a name when one is found.
