Sub topic 2
Getting the Value Out Safely
An Optional is a box that may hold a value. At some point you need the value itself. This chapter shows how to take it out without crashing your program.
Getting the Value Out Safely
The get method returns the value. If the box is empty, it throws a NoSuchElementException (an error that stops the program). Because of that risk, beginners should use these safer methods instead:
orElse(x)returns the value, or the defaultxif the box is empty. A default is a backup value.orElseGet(supplier)returns the value, or calls the supplier to make a default. A supplier is a small function that takes no input and returns a value.orElseThrow(supplier)returns the value, or throws the exception you choose.
Doing Something Only When a Value Exists
Sometimes you want to act on the value without taking it out. ifPresent runs your code only when a value exists. ifPresentOrElse (Java 9 and later) also runs backup code when the box is empty.
import java.util.Optional;
public class RetrieveDemo {
public static void main(String[] args) {
Optional<String> city = Optional.empty();
System.out.println(city.orElse("Unknown")); // Unknown
System.out.println(city.orElseGet(() -> "Computed")); // Computed
try {
city.orElseThrow(() -> new IllegalStateException("No city"));
} catch (IllegalStateException e) {
System.out.println(e.getMessage()); // No city
}
Optional<String> user = Optional.of("grace");
user.ifPresent(u -> System.out.println("Hello, " + u)); // Hello, grace
city.ifPresentOrElse(
c -> System.out.println("City: " + c),
() -> System.out.println("No city given")); // No city given
}
}orElse vs orElseGet: When Defaults Are Computed
orElse builds its default every time, even when the value is present. This is called eager. orElseGet builds the default only when the box is empty. This is called lazy. If making the default is slow, for example a database call, use orElseGet.
import java.util.Optional;
public class EagerLazyDemo {
static String makeDefault() {
System.out.println("Making default...");
return "Unknown";
}
public static void main(String[] args) {
Optional<String> name = Optional.of("Ada");
String a = name.orElse(makeDefault()); // prints "Making default..."
String b = name.orElseGet(EagerLazyDemo::makeDefault); // prints nothing
System.out.println(a + " " + b); // Ada Ada
}
}Exercise
Optional<String> o = Optional.of("x"); What does o.orElse(slow()) do that o.orElseGet(() -> slow()) does not?
Show answer
orElse calls slow() even though the value "x" is present, because the argument is computed before the method runs. orElseGet never calls slow() here, because the box is not empty.