Optional.isPresent()
Checks whether an `Optional` holds a value.
Available since: Java 8
Syntax
boolean isPresent()
boolean isEmpty()Return value
boolean`isPresent()` returns `true` if a value is present; `isEmpty()` (Java 11) is the opposite.
Examples
Checking and reading:
void main() {
Optional<String> found = Stream.of("pen", "book").filter(s -> s.startsWith("b")).findFirst();
if (found.isPresent()) {
IO.println("Found " + found.get());
}
IO.println(Optional.empty().isEmpty());
}Output:
Found book
trueNotes
The isPresent() + get() pair works, but ifPresent(), orElse() or map() are usually shorter and safer. Calling get() on an empty Optional throws NoSuchElementException.
See also
- Optional.ifPresent() — Runs an action only if a value is present.
- Optional.orElse() — Returns the value, or a fallback if there is none.
- Optional.empty() — Returns an empty `Optional` — no value.
In the tutorial
- Optional — The Optional class in Java: a value that may be absent, creating it with of and empty, orElse, map, ifPresent and orElseThrow.