Home > database >  Return Optional.empty instead of Optional[null] in Optional.map
Return Optional.empty instead of Optional[null] in Optional.map

Time:02-01

In the below code, if customerInfo is not present, it returns Optional[null] and hence customerInfo.get(name).textValue() returns a NPE. Is there a way to make map(data -> data.get("customerInfo")) return Optional.empty() instead of Optional[null]? Here the null within Optional[null] is a NullNode object.

  Optional<JsonNode> orderData = getOrderData() // API Call

  orderData.map(data -> data.get("customerInfo"))
  .map(customerInfo -> customerInfo.get(name).textValue());

CodePudding user response:

You seem to be misinterpreting the problem you're having. The NullPointerException occurs because customerInfo.get(name) is null, so customerInfo.get(name).textValue() is trying to call the textValue() method on a null reference.

To fix this, you can split that call to map into two calls, like so:

orderData.map(data -> data.get("customerInfo"))
  .map(customerInfo -> customerInfo.get(name))
  .map(customer -> customer.textValue());

This way, if customerInfo.get(name) is null, then the resulting Optional will be empty, and that last lambda won't be executed.

  • Related