William Johnson
William Johnson

Reputation: 55

Combining Optional.ofNullable() null check in java

I am doing a null check using Optional.ofNullable() for an API response where all the fields are optional (for lack of a better word), but we want to map the ones that are present, which may differ on each response payload.

Optional.ofNullable(details.getBadResponse()).map(property -> property.getResponseStatus()).ifPresent(property -> {
    responseData.setRawResponseCode(property.getResponseStatus());
});
Optional.ofNullable(details.getBadResponse()).map(property -> property.getErrorMessage()).ifPresent(property -> {
    responseData.setResponseMessage(property.getErrorMessage());
});
Optional.ofNullable(details.getBadResponse()).map(property -> property.getErrorReason()).ifPresent(property -> {
    responseData.setResponseCode(property.getErrorReason(), "serviceError");
});
Optional.ofNullable(details.getBadResponse()).map(property -> property.getId()).ifPresent(property -> {
    responseData.setRecordId(StringUtils.defaultString(property.getId(), StringUtils.EMPTY));
});

Is it possible to combine these statements into one Optional.ofNullable check on the details object (where details is the response object) to have the code be more clean?

Upvotes: 0

Views: 208

Answers (0)

Related Questions