Optional Keyword – Java 8

Java 8 has introduced java.util.Optional class to find a value present or absent.

Normally Java developers do “not null” check to identify whether the Object is null or to be used further for business logic. In a Enterprise application, lot of null checks present as each meaning object is checked, which makes the code messy.

Java 8 introduced Optional package so developers can develop neat code in developing any API or enterprise applications.

Optional class avoid any Null Pointer exceptions since Optional always check and returns empty if not present.

Ways of creating Optional Object:


No Value for Unknown Car Object
No Value for emptyObject

Map & flatMap

Optional also provide methods like flatMap() and map() methods to fetch internal Object values.

Optional.map if the function returns the plain object
Optional.flatMap if the function returns an Optional Object



Leave a Reply

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