Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return Optional.empty instead of Optional[null] in Optional.map

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());

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading