If you have an existing Object in Java that you want to convert to type Optional then you can make use of the of() or ofNullable() static methods from the Optional class.
Example:
import java.util.Optional;
public class Example {
public static void main(String[] args) {
String strObject1 = "Coe2care";
Optional optionalValue1 = Optional.of(strObject1);
String strObject2 = null;
Optional optionalValue2 = Optional.ofNullable(strObject2);
if (optionalValue1.isPresent()) {
System.out.println("Value: " + optionalValue1.get());
} else {
System.out.println("Value is null");
}
if (optionalValue2.isPresent()) {
System.out.println("Value: " + optionalValue2.get());
} else {
System.out.println("Value is null");
}
}
}
Output:
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!