Create an Optional Object from a Nullable Object

Java 8 introduced the java.util.Optional<T> class to reflect an optional value. The following example demonstrates how to convert a previously (pre-Java 8) Nullable object to an Optional object Java 8 onwards.

The following is a snapshot of a trivial class that has a nullable object middleName. Code Snippets that follow it provide how we provide methods that convert this Nullable object to an Optional object.


import java.util.Optional;
                            
public class Name {
                            
    private String middleName;
                            
    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }
                            
    /**
    * Convert the String object to an Optional<String> object
    * 
    * @return an Optional String
    */
    public Optional<String> getOptionalMiddleName() {
        return Optional.ofNullable(middleName);
    }
                            
    /**
    * 
    * @return the middle name when it exists, or an empty string when it
    *         doesn't
    */
    public String getMiddleName() {
        return getOptionalString(middleName);
    }
                            
    /**
    * @return a string value when it exists or an empty value when it doesn't
    *         exist
    */
    public String getOptionalString(String optional) {
        return Optional.ofNullable(optional).orElse("");
    }
                            
}					

public class OptionalExample {
                            
    public static void main(String[] args) {
        Name name = new Name();
        System.out.println("Middle Name: " + name.getOptionalMiddleName());
        System.out.println("Middle Name: " + name.getOptionalString(name.getMiddleName()));
        name.setMiddleName("Test");
        System.out.println("Middle Name: " + name.getOptionalString(name.getMiddleName()));
    }
                                
}