To check if a Java Optional
has a value, you can use the isPresent()
or isEmpty()
methods:
- Using
isPresent()
This method returnstrue
if theOptional
contains a value, andfalse
if it is empty.Optional<String> optional = Optional.of("Hello"); if (optional.isPresent()) { System.out.println("Value is present: " + optional.get()); } else { System.out.println("Value is not present."); }
- Using
isEmpty()
Starting from Java 11, you can use theisEmpty()
method, which is the opposite ofisPresent()
. It returnstrue
if theOptional
is empty, andfalse
otherwise.Optional<String> optional = Optional.empty(); if (optional.isEmpty()) { System.out.println("Value is not present."); } else { System.out.println("Value is present: " + optional.get()); }
- Using
ifPresent()
If you only need to execute code when the value is present, you can use theifPresent()
method, which takes a lambda expression or a method reference to process the value.Optional<String> optional = Optional.of("Hello"); optional.ifPresent(value -> System.out.println("Value: " + value));
Best Practices
- Avoid calling
optional.get()
without checking if the value is present; otherwise, it will throw aNoSuchElementException
if theOptional
is empty. - Use
ifPresent()
wherever possible to handle the value directly, avoiding explicit checks withisPresent()
.