Java Tutorial · Advanced Java · Lesson 33 of 37
Java Optional
Represent 'maybe a value' explicitly and avoid NullPointerException.
Optional
Optional<T> is a container that holds a value or is empty. Returning Optional from a method makes "might not exist" part of its type, so callers can't forget to handle it:
import java.util.Map;
import java.util.Optional;
public class Main {
public static void main(String[] args) {
System.out.println(findEmail(1).orElse("no email"));
System.out.println(findEmail(2).orElse("no email"));
System.out.println(findEmail(1).map(String::toUpperCase).orElse("-"));
findEmail(1).ifPresent(e -> System.out.println("Sending to " + e));
System.out.println(findEmail(2).isEmpty());
try {
findEmail(3).orElseThrow(() -> new IllegalArgumentException("user 3 has no email"));
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
static final Map<Integer, String> EMAILS = Map.of(1, "[email protected]");
static Optional<String> findEmail(int userId) {
return Optional.ofNullable(EMAILS.get(userId));
}
}
Output
[email protected] no email [email protected] Sending to [email protected] true user 3 has no email
Run this on your computer — see “Get Started” for setup.
Good practice
- Use
Optionalas a return type, not for fields or parameters. - Prefer
orElse,orElseGet,orElseThrow,mapandifPresentoverisPresent()+get(). - Never return
nullfrom a method declared to returnOptional.
Test yourself
Which method returns a default when the Optional is empty?
get()orElse()isPresent()of()
Show answer
Answer: orElse()