获取可选对象的字段或返回 null [英] Get field of optional object or return null
本文介绍了获取可选对象的字段或返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有可选对象:
Optional<Detail> newestDetail;
我想返回 newestDetail.getId()
或者如果 newestDetail
为空返回 null
.
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;
推荐答案
将值映射到带有 id 字段的 Optional
并将其转换为 null
值,如果它是空的:
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);
这篇关于获取可选对象的字段或返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文