How to create Optional object?

Optional Static Factories

1. Overview

In this article we will discuss 3 different ways to create Optional object. Java has provided us with 3 different static factories. Let us take a deeper look at these methods.

This article is part of ongoing series of Optional. Read about it more here.

2. Creating Optional without value

empty() method creates an Optional object for which the value is absent. This is an extremely important method as it denotes that the operation performed doesn’t return a value or a value is absent for the operation that was performed.

Optional<String> optStr = Optional.empty();
 
Assert.assertFalse(optStr.isPresent());

3. Creating Optional with value

of() method is a static factory defined in Optional class which creates instance of Optional if the value passed is not null. The method throws NullPointerException if the value passed is null.

This method must be used only if you can guarantee that the value will not be null.

Optional<String> optStr = Optional.of("value");
 
optStr.ifPresent(System.out::print); //Prints the value on console

4. ofNullable() value may or may not be absent

ofNullable() method creates an Optional object by combining the power of empty() and of() method.

If the value passed is null then empty() Optional is returned else a new Optional object is created using Optional.of(value).

It might be tempting to ditch empty() and of() methods in favor of ofNullable() but this can be a trap as the code-base would become hard to understand.

Remember while ofNullable() combines the functionality of empty() and of() methods it doesn’t clearly state the intent of Optional object. The intent of empty() and of() methods is clear which means value is absent and value is present, respectively. The intent of ofNullable() is not that clear.

Optional<String> optStr = Optional.ofNullable("value");
 
Optional<String> optEmpty = Optional.ofNullable(null);

5. Conclusion

In this article, we saw 3 different static factories to create Optional object.

  • Optional.empty() creates an Optional where value is absent.
  • Optional.of(T) creates an Optional where value is present.
  • Optional.ofNullable() creates an Optional where value may be present.

Leave a Reply

Your email address will not be published. Required fields are marked *