Get field of optional object or return null

Rudziankoŭ :

I have optional object:

Optional<Detail> newestDetail;

I would like to return newestDetail.getId() or if newestDetail is null return null.

Do we have more sophisticated approach of doing this, than following?

return newestDetail.isPresent()?newestDetail.get().getId():null;
Henrik Aasted Sørensen :

Map the value to an Optional with the id field and turn that one into a null value if it is empty:

return newestDetail.map(Detail::getId).orElse(null);

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=442013&siteId=1