Search code examples
javaoption-type

Fetching value from nested optional elements in Java


Is there a more concise way of fetching the orderLabel information when it is present in an optional object which present under another optional object.

Optional<Order> maybeOrderInfo = getOrderInfo(); // API Call
Optional<String> orderLabel = maybeOrderInfo.isPresent()
  ? maybeOrderInfoPresent
    .get()
    .genericOrderInfo()
    .map(orderInfo -> orderInfo.get("orderLabel"))
    .or(() -> Optional.empty())
  : Optional.empty();

Solution

  • Use Optional#flatMap.

    Optional<String> orderLabel = getOrderInfo().flatMap(Order::genericOrderInfo)
                                   .map(orderInfo -> orderInfo.get("orderLabel"));