We have the isPresent() and ifPresent() methods to help us detect if Optional contains some value or not.
Optional isPresent() method
The isPresent() method returns true if there is a value present in the Optional, otherwise false.
Using it, we can avoid getting an exception when trying to get the value from an empty Optional. So the best practice is always to first check if the value is present in the Optional.
Example:
class Test { public static void main(String[] args) { Optional<String> optional = Optional.ofNullable("someValue"); if (optional.isPresent()) { System.out.println("The value is: " + optional.get()); } else { System.out.println("Optional is empty."); } } }
Output: The value is: someValue
Optional ifPresent() method
The ifPresent() method – If a value is present, invoke the specified Consumer with the value. Otherwise, do nothing.
Example:
class Test { public static void main(String[] args) { Optional<String> optional = Optional.ofNullable("someValue"); optional.ifPresent(value -> System.out.println(value)); } }
Output: someValue
I hope this tutorial was helpful to you. To learn more, check out other tutorials that teach Java Optional.
Happy learning!