Having been using Java 8 now for 6+ months or so, I\'m pretty happy with the new API changes. One area I\'m still not confident in is when to use Optional
. I se
Optional
class lets you avoid to use null
and provide a better alternative:
This encourages the developer to make checks for presence in order to avoid uncaught NullPointerException
's.
API becomes better documented because it's possible to see, where to expect the values which can be absent.
Optional
provides convenient API for further work with the object:
isPresent(); get(); orElse(); orElseGet(); orElseThrow(); map(); filter(); flatmap().
In addition, many frameworks actively use this data type and return it from their API.