Careeroza
Creating and Reading Optional
Create
| Method | Use when |
|---|---|
Optional.of(value) | value is surely not null (throws NPE if it is) |
Optional.ofNullable(value) | value may be null |
Optional.empty() | no value |
Read
| Method | Behaviour when empty |
|---|---|
orElse(other) | returns other (other is always evaluated) |
orElseGet(supplier) | calls supplier only when empty (lazy) |
orElseThrow() / orElseThrow(supplier) | throws NoSuchElementException / your exception |
ifPresent(consumer) | does nothing |
ifPresentOrElse(consumer, runnable) | runs the runnable |
isPresent(), isEmpty() | false / true |
get() | throws — avoid; use orElseThrow() instead |
orElse vs orElseGet
Example
orElse always runs its argument, even when a value is present. Use orElseGet for anything expensive (DB call, object creation).
import java.util.*;
public class Main {
static String loadDefaultFromDb() {
System.out.println(" (expensive DB call!)");
return "default-city";
}
public static void main(String[] args) {
Optional<String> city = Optional.of("Hyderabad");
System.out.println("orElse:");
System.out.println(city.orElse(loadDefaultFromDb()));
System.out.println("orElseGet:");
System.out.println(city.orElseGet(Main::loadDefaultFromDb));
Optional<String> empty = Optional.empty();
empty.ifPresentOrElse(c -> System.out.println("City " + c), () -> System.out.println("No city set"));
System.out.println("isEmpty: " + empty.isEmpty());
try {
empty.orElseThrow(() -> new IllegalArgumentException("City is required"));
} catch (IllegalArgumentException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}Output
orElse: (expensive DB call!) Hyderabad orElseGet: Hyderabad No city set isEmpty: true Caught: City is required