tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java 8 Features > Stream API > Java 8 Optional Chaining with map and flatMap

Java 8 Optional Chaining with map and flatMap

Author: Venkata Sudhakar

Optional is a container object in Java 8 that may or may not hold a value. Its purpose is to make the possibility of a missing value explicit in the API, forcing the caller to handle it rather than accidentally calling a method on null. The real power of Optional is not just wrapping a value - it is the ability to chain transformations using map() and flatMap() so you can safely navigate nested objects without a chain of null checks.

map() transforms the value inside an Optional if one is present, returning a new Optional with the result. If the Optional is empty, map() does nothing and returns an empty Optional. flatMap() works the same way but is used when the transformation function itself returns an Optional, preventing you from ending up with Optional of Optional. orElse() and orElseGet() extract the final value, providing a default if the Optional is empty.

The below example shows how Optional chaining replaces nested null checks when navigating an Order to get the customer city.


It gives the following output,

Old way: Mumbai
Optional way: Mumbai
No customer: Unknown
No address: Unknown

It gives the following output,

Domain: example.com
Missing: domain-not-found

Use map() when your lambda returns a plain value. Use flatMap() when your lambda returns an Optional. Never call Optional.get() without first checking isPresent() - it defeats the purpose of Optional entirely. Prefer orElse("default") for constant defaults and orElseGet(() -> computeDefault()) when the default is expensive to compute since orElseGet is lazy.


 
  


  
bl  br