Sub topic 7
orElse vs orElseGet: When Defaults Are Computed
In the last chapter, you used orElse and orElseGet to get a value out of an Optional. Both give you a default when the Optional is empty. They look almost the same, but they differ in one way that matters: when the default value gets made.
This chapter shows that difference and helps you pick the right method.
Two Words: Eager and Lazy
Two terms explain the difference:
- Eager means "done right away, whether you need it or not."
- Lazy means "done only when it is actually needed."
orElse is eager. orElseGet is lazy.
How orElse Works
orElse takes a ready-made value. Java must build that value before it calls orElse. So the default is always created, even when the Optional already holds a value.
String name = maybeName.orElse("Guest");Here the default is just the text "Guest". Making it costs almost nothing, so eager is fine.
How orElseGet Works
orElseGet takes a Supplier. A Supplier is a small function that takes no input and returns a value. You usually write it as a lambda, like () -> "Guest".
orElseGet keeps the Supplier and calls it only if the Optional is empty. If a value is present, the Supplier never runs.
String name = maybeName.orElseGet(() -> "Guest");Seeing the Difference
The program below has a method that prints a message each time it runs. That way you can see exactly when the default is computed.
import java.util.Optional;
public class DefaultTimingDemo {
static String expensiveDefault() {
System.out.println(" Computing default...");
return "Guest";
}
public static void main(String[] args) {
Optional<String> name = Optional.of("Ada");
System.out.println("Using orElse:");
String a = name.orElse(expensiveDefault());
System.out.println(" Result: " + a);
System.out.println("Using orElseGet:");
String b = name.orElseGet(() -> expensiveDefault());
System.out.println(" Result: " + b);
}
}Output:
Using orElse:
Computing default...
Result: Ada
Using orElseGet:
Result: AdaLook closely. The Optional holds "Ada", so both calls return "Ada". But orElse still ran expensiveDefault(). Its work was thrown away. orElseGet skipped it.
Why It Matters
Wasted work is a small problem when the default is a plain string. It becomes a real problem when the default:
- is slow to build, such as a database call or a file read
- creates a large object
- has a side effect, which is something a method does beyond returning a value, like writing a log entry, sending a message, or saving a record
Choosing Between Them
| Situation | Use | Example |
|---|---|---|
| Default is a constant or simple value | `orElse` | `orElse("Unknown")` |
| Default is a variable you already have | `orElse` | `orElse(defaultName)` |
| Default needs a method call that does work | `orElseGet` | `orElseGet(() -> loadFromDb())` |
| Default has side effects | `orElseGet` | `orElseGet(this::createUser)` |
You may wonder why you shouldn't just use orElseGet everywhere. You can, but orElse("Unknown") is shorter and easier to read. For simple values, the lambda adds noise and saves nothing.
Exercise
An Optional<String> called email holds "[email protected]". What does this code print, and why?
String result = email.orElse(sendWelcomeEmail());
Assume sendWelcomeEmail() prints "Email sent!" and returns "none".
Show answer
It prints "Email sent!", and result is "[email protected]". orElse is eager, so Java calls sendWelcomeEmail() before orElse runs, even though a value is present. To avoid sending the email, write email.orElseGet(() -> sendWelcomeEmail()).
Exercise
Which method fits better for each default? (1) the number 0, (2) a call to readConfigFile(), (3) a String variable named fallback.
Show answer
(1) orElse, because 0 is a constant. (2) orElseGet, because reading a file is slow work that should only happen when needed. (3) orElse, because the variable already exists and costs nothing to pass.