Sub topic 6
Doing Something Only When a Value Exists
Sometimes you don't need the value inside an Optional handed back to you. You just want to do something with it if it is there, such as print it, save it, or send it in an email. If the Optional is empty, you want to skip that step or do something else.
Java gives you two methods for this:
ifPresentruns your code only when a value exists.ifPresentOrElseruns one piece of code when a value exists and a different piece when it does not. This method was added in Java 9.
This chapter shows how both methods work, why they are often clearer than checking with isPresent, and which mistakes to avoid.
The Old Way: Check, Then Get
In the earlier chapter on checking presence, you saw isPresent. A common first attempt looks like this:
import java.util.Optional;
public class CheckThenGet {
public static void main(String[] args) {
Optional<String> user = Optional.of("grace");
if (user.isPresent()) {
System.out.println("Hello, " + user.get());
}
}
}This works. It has two weak spots, though:
- You name the Optional twice: once to check it and once to get the value.
- Someone could later move the
get()call outside theifblock. Thenget()would throw aNoSuchElementExceptionwhen the Optional is empty.
The ifPresent method joins the check and the action into one step. Since you never call get(), that mistake can't happen.
Two Small Building Blocks: Consumer and Runnable
Both methods take small pieces of code as arguments. Java describes those pieces with two interfaces. An interface is a type that names what a method must look like without giving its body.
- A Consumer is a piece of code that takes one value and returns nothing. Its full name is
java.util.function.Consumer<T>. "Consumer" means it uses up the value, for example by printing it. - A Runnable is a piece of code that takes nothing and returns nothing. Its full name is
java.lang.Runnable. It just runs.
You rarely write these types by name. You usually pass a lambda, which is a short, unnamed function written with an arrow (->). For example:
| Code | Type | Meaning |
|---|---|---|
| `u -> System.out.println(u)` | Consumer | Take `u` and print it |
| `System.out::println` | Consumer | Same thing, written as a method reference |
| `() -> System.out.println("No user")` | Runnable | Take nothing and print a message |
A method reference like System.out::println is a shorter way to write a lambda that just calls one existing method.
ifPresent: Act Only When There Is a Value
The ifPresent method takes a Consumer. If the Optional holds a value, Java passes that value to your Consumer. If the Optional is empty, nothing happens 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
user.ifPresent(System.out::println); // prints: grace
}
}Here is what happens step by step:
userholds"grace", so the lambda runs withuset to"grace".nobodyis empty, so the lambda is never called. The line is skipped quietly.- The method reference
System.out::printlnacts likeu -> System.out.println(u).
ifPresentOrElse: Handle Both Cases
Often an empty Optional should still trigger something, like a message saying nothing was found. Before Java 9, you had to go back to an if/else with isPresent. Java 9 added ifPresentOrElse, which takes two arguments:
- A Consumer that runs if a value is present.
- A Runnable that runs if the Optional is empty.
Exactly one of them runs, never both.
import java.util.Optional;
public class IfPresentOrElseDemo {
static void greet(Optional<String> user) {
user.ifPresentOrElse(
u -> System.out.println("Hello, " + u),
() -> System.out.println("No user"));
}
public static void main(String[] args) {
greet(Optional.of("grace")); // Hello, grace
greet(Optional.empty()); // No user
}
}The second argument has empty parentheses, (), because a Runnable takes no input. There is no value to pass in when the Optional is empty.
A Worked Example: Looking Up an Order
Here is a slightly bigger program. A method looks up an order by its ID and returns an Optional<String>. The program then reports each result.
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class OrderReport {
static final Map<Integer, String> ORDERS = Map.of(
101, "Blue mug",
102, "Desk lamp");
static Optional<String> findOrder(int id) {
return Optional.ofNullable(ORDERS.get(id));
}
public static void main(String[] args) {
List<Integer> ids = List.of(101, 999, 102);
for (int id : ids) {
findOrder(id).ifPresentOrElse(
item -> System.out.println("Order " + id + ": " + item),
() -> System.out.println("Order " + id + ": not found"));
}
// Only print orders that exist; ignore missing ones.
findOrder(102).ifPresent(item -> System.out.println("Shipping " + item));
findOrder(555).ifPresent(item -> System.out.println("Shipping " + item));
}
}Output:
Order 101: Blue mug
Order 999: not found
Order 102: Desk lamp
Shipping Desk lampNotice two things:
Map.getreturnsnullfor a missing key, sofindOrderwraps the result withOptional.ofNullable. You learned this in the chapter on creating Optionals.- The lambdas use
idfrom the loop. Java allows this because eachidis effectively final, meaning it is never reassigned after it gets its value.
Common Mistakes and Edge Cases
Trying to change a local variable inside the lambda
A lambda can read local variables, but it can't reassign them. This code does not compile:
import java.util.Optional;
public class BrokenCount {
public static void main(String[] args) {
Optional<String> user = Optional.of("grace");
int count = 0;
user.ifPresent(u -> count++); // compile error: count must be effectively final
System.out.println(count);
}
}If you need a result out of an Optional, don't use ifPresent. Use a method that returns a value, such as orElse, or map (covered in a later chapter):
import java.util.Optional;
public class FixedCount {
public static void main(String[] args) {
Optional<String> user = Optional.of("grace");
int count = user.isPresent() ? 1 : 0;
String name = user.orElse("guest");
System.out.println(count + " " + name); // 1 grace
}
}Expecting a return value
Both methods return void, meaning they return nothing. You can't write String s = opt.ifPresent(...), and you can't chain another Optional method after them. Treat them as the final step: you have decided what to do, and you do it.
Exceptions inside your action
If your Consumer or Runnable throws an exception, the exception travels out of ifPresent or ifPresentOrElse to the code that called it. The Optional does not catch it for you.
import java.util.Optional;
public class ActionThrows {
public static void main(String[] args) {
try {
Optional.of("x").ifPresent(v -> {
throw new IllegalArgumentException("Bad value: " + v);
});
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage()); // Bad value: x
}
}
}Passing null as the action
Don't pass null instead of a lambda. If ifPresent(null) is called on an Optional that has a value, it throws a NullPointerException. On an empty Optional the action is never needed, so no error appears. That makes the bug easy to miss in testing. The same rule covers each of the two arguments of ifPresentOrElse: the error appears only when Java tries to use the missing action.
Long blocks inside the lambda
A lambda can hold many lines inside { }, but a long one is hard to read. If your action grows past a few lines, move it into its own method and pass a method reference, such as opt.ifPresent(this::sendWelcomeEmail).
Choosing the Right Tool
| Situation | Use |
|---|---|
| Do something with the value; ignore the empty case | `ifPresent` |
| Do one thing if present, another if empty | `ifPresentOrElse` (Java 9+) |
| Need a value back, with a default | `orElse` or `orElseGet` |
| Empty means an error | `orElseThrow` |
| On Java 8 and need both branches | `if (opt.isPresent()) ... else ...` |
Exercises
Exercise
What does this code print? Optional<String> pet = Optional.empty(); pet.ifPresent(p -> System.out.println("Pet: " + p)); System.out.println("Done");
Show answer
It prints only "Done". The Optional is empty, so the lambda passed to ifPresent never runs.
Exercise
Rewrite this code using ifPresentOrElse: if (city.isPresent()) { System.out.println("City: " + city.get()); } else { System.out.println("No city given"); }
Show answer
city.ifPresentOrElse(c -> System.out.println("City: " + c), () -> System.out.println("No city given")); The first lambda is a Consumer that receives the value. The second is a Runnable with empty parentheses because there is no value in the empty case.
Exercise
A teammate writes String upper = name.ifPresent(n -> n.toUpperCase()); Why doesn't this compile, and what should they write instead?
Show answer
ifPresent returns void, so there is nothing to assign to upper. To get a value back, use a method that returns one, for example String upper = name.map(String::toUpperCase).orElse(""); or check with isPresent and use orElse.
Exercise
Your project runs on Java 8. Which of the two methods from this chapter can you use, and how do you handle both the present and empty cases?
Show answer
Only ifPresent exists in Java 8. ifPresentOrElse was added in Java 9. For both cases on Java 8, use if (opt.isPresent()) { ... opt.get() ... } else { ... }.
Exercise
Why might ifPresent(null) pass your tests and then fail in production?
Show answer
The action is only used when a value is present. If your tests only use empty Optionals, the null action is never touched and no error appears. When real data arrives with a value, Java tries to run the null action and throws a NullPointerException.