Get field of optional object or return null

浪尽此生 提交于 2019-12-04 19:16:20

问题


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;

回答1:


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


来源:https://stackoverflow.com/questions/47714105/get-field-of-optional-object-or-return-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!