Hitchhiker’s guide to Java Optional

Basic usage

When to use it and when not

  • Never use Optional as class variable. It isn’t serializable.
  • Never use it as input parameter of a method. There are multiple problems with it. The caller must wrap the value which is inconvinient. The Optional reference can also be null so we have to check it anyway.
  • Never use it for wrapping collections directly (Lists, Sets, Maps..). Use empty collection instead of null and Optional.
  • Don’t use it as the return value of a private method. It increases the complexity and most of the time the caller method should unwrap it anyway.

Constructing Optional and Retrieving its value

Create Optional
Retrieve value


Null check chain



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store