Modern Java in Action 5 - Optional


Null problem

Reasons why null is problematic:

  • source of coding errors (missing checks)
  • does not correctly model absence of value (null has no meaning)
  • breaks Java philosophy of hiding pointers (null is a pointer which is NOT hidden)

Handling in other languages



Three static methods may create instances of Optional:

  • Optional.empty() - creates empty instance
  • Optional.of(T) - returns Optional with given non-null value
  • Optional.ofNullable(T) - returns either Optional with T value or Optional.empty() if value is null

java.util.Optional in Java 17 - compared to Java 8 - gains the following:

Version Method Desc
9 ifPresentOrElse if present, gives value to Consumetr<T>, else tuns given Runnable
9 or returns Optional that will use alternative Optional that will be used if this one is empty
9 stream() if value is present, returns a sequential Stream with single value or empty Stream
10 orElseThrow if present, returns value, else, throws Exception provided by Supplier<? extends Exception>
11 isEmpty returns true if value is present

A chain of Optionals

In order to be able to navigate through a series of Optional values one needs to remember the difference between map and flatmap:

  • if a mapping function returns value, you want to use map
  • if a mapping function returns Optional, you want to use flatmap

Here, person’s car and car’s insurance are modelled as Optional values, hence the use of flatmap:

public String getCarInsuranceName(Optional<Person> person) {
    return person.flatMap(Person::getCar)