ifPresent and isPresent
- Java course
- Advanced
- Lesson 11/82
- 5 min
Learn checks with ifPresent and isPresent.
Conditional action: ifPresent
ifPresent(Consumer) runs the given Consumer when the value is present; it does nothing otherwise. This is the cleanest way to use the value without an explicit isPresent check.
Example: opt.ifPresent(value -> System.out.println(value)). If opt is present the value is printed; if empty, nothing happens. ifPresent fits side-effecting operations; it is not for cases that expect a return value. When you also want an action for the absent case, use ifPresentOrElse.
Avoiding get
Optional.get() returns the value directly; but it throws NoSuchElementException when the value is absent. Calling get without a check is therefore risky.
Prefer ifPresent, orElse or orElseThrow instead. Example: opt.ifPresent(v -> use(v)). The empty case is handled explicitly; no unexpected error. If you are certain a value exists, get still works; in that case a comment explaining why is good practice.
Practice Print a value with ifPresent
Create an Optional<String> with Optional.of("Mia"). Use ifPresent with a lambda to print the value prefixed by "Hello " via System.out.println.
Starter code
import java.util.Optional;
// Wrap "Mia" with Optional.of
// Print with a lambda via ifPresent
// Output: Hello MiaSample solution
import java.util.Optional;
public class IfPresentExample {
public static void main(String[] args) {
Optional<String> name = Optional.of("Mia");
name.ifPresent(n -> System.out.println("Hello " + n));
}
}Expected output
Hello Mia
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the Optional inspection methods
| Term | Meaning |
|---|---|
ifPresent |
Takes a Consumer |
isPresent |
Returns boolean |
isEmpty |
Is it empty |
ifPresentOrElse |
Takes two Consumers |
2 Which method returns a boolean?
- ifPresent
- get
- isPresent Correct answer
- map
Explanation: isPresent returns the value's presence as a boolean.
3 Complete the isPresent check
boolean present = opt.____();
boolean present = opt.isPresent();
Explanation: isPresent checks the value's presence.