Sub topic 6
Doing Something Only When a Value Exists
Sometimes you don't need the value back from an Optional. You only want to do something with it, such as print it, save it, or send it, and only when it is there. Optional has two methods for this: ifPresent and ifPresentOrElse.
The Old Way: Check, Then Get
In the last chapter you saw isPresent. You might be tempted to write code like this:
import java.util.Optional;
public class OldWayDemo {
public static void main(String[] args) {
Optional<String> user = Optional.of("grace");
if (user.isPresent()) {
System.out.println("Hello, " + user.get());
}
}
}This works. But it takes two steps, and you must remember to check before you call get. If you forget the check, get throws an exception on an empty Optional. That is the same kind of mistake Optional was meant to stop.
ifPresent: Act When There Is a Value
ifPresent does the check and the action in one step. You hand it a Consumer. A Consumer is a piece of code that takes one value and does something with it but returns nothing. You usually write it as a lambda, like u -> System.out.println(u).
Here is what happens:
- If the Optional holds a value,
ifPresentruns your Consumer with that value. - If the Optional is empty,
ifPresentdoes nothing at all.
import java.util.Optional;
public class IfPresentDemo {
public static void main(String[] args) {
Optional<String> user = Optional.of("grace");
Optional<String> nobody = Optional.empty();
user.ifPresent(u -> System.out.println("Hello, " + u)); // prints Hello, grace
nobody.ifPresent(u -> System.out.println("Hello, " + u)); // prints nothing
}
}Notice that you never call get. The value is passed into the lambda as u, so there is no chance to grab a missing value by accident.
You can also use a method reference. user.ifPresent(System.out::println) prints the value if one exists.
ifPresentOrElse: Handle Both Cases
Often you want to do one thing when a value exists and something else when it doesn't. Java 9 added ifPresentOrElse for this. It takes two arguments:
- A Consumer that runs when a value is present.
- A Runnable that runs when the Optional is empty. A Runnable is code that takes no input and returns nothing. You write it as
() -> ....
import java.util.Optional;
public class ActionDemo {
public static void main(String[] args) {
Optional<String> user = Optional.of("grace");
user.ifPresent(u -> System.out.println("Hello, " + u));
Optional.<String>empty().ifPresentOrElse(
u -> System.out.println("Hello, " + u),
() -> System.out.println("No user"));
}
}Output:
Hello, grace
No userThe second Optional is empty, so the Runnable runs and prints "No user".
When to Use Which
| Situation | Method |
|---|---|
| Do something only if there is a value; ignore the empty case | `ifPresent` |
| Do one thing if there is a value, another if there isn't | `ifPresentOrElse` |
| You need a value back to keep using | `orElse`, `orElseGet`, or `orElseThrow` |
These two methods return nothing (void). Use them for actions with side effects, such as printing, logging, or saving. If you need a result to work with, use the retrieval methods from the earlier chapter.
Exercises
Exercise
What does this code print? Optional.<String>empty().ifPresent(s -> System.out.println("Got " + s));
Show answer
It prints nothing. The Optional is empty, so ifPresent never runs the lambda.
Exercise
Rewrite this using ifPresentOrElse: if (city.isPresent()) { System.out.println(city.get()); } else { System.out.println("No city"); }
Show answer
city.ifPresentOrElse(c -> System.out.println(c), () -> System.out.println("No city")); The first lambda gets the value when it is present, and the second runs when the Optional is empty.
Exercise
Why is ifPresent safer than calling isPresent and then get?
Show answer
ifPresent passes the value straight into your code only when it exists, so you never call get. With the check-then-get style, forgetting the check makes get throw an exception on an empty Optional.