15

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;
Rudziankoŭ
  • 10,681
  • 20
  • 92
  • 192
  • 2
    as a side note, there are *many* more convince methods inside `Optional`, see this: https://www.youtube.com/watch?v=fBYhtvY19xA – Eugene Dec 10 '17 at 19:46

1 Answers1

33

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);
Henrik Aasted Sørensen
  • 6,966
  • 11
  • 51
  • 60