How to create an Optional from existing Object in Java?

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:

Value: Coe2care
Value is null

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!