Java 'Optional.get()' 没有 'isPresent()' 检查
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38725445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
'Optional.get()' without 'isPresent()' check
提问by Dims
I have the following search code in Java:
我在 Java 中有以下搜索代码:
return getTableViewController().getMe().getColumns().stream().filter($->Database.equalsColumnName($.getId(), columnId)).findFirst().get();
I was wishing to find column by name and return first one found.
我希望按名称查找列并返回找到的第一个列。
I understand there is a case when nothing found and it should be processed, but how?
我知道有一种情况没有找到并且应该处理它,但是如何处理?
Is this what it wants by this swearing:
这是它想要的咒骂吗:
'Optional.get()' without 'isPresent()' check
?
?
How to fix? I wish to return null
if nothing found.
怎么修?null
如果没有找到,我希望返回。
UPDATE
更新
Okay, okay, I just didn't realize, that findFirst()
returns Optional
.
好吧,好吧,我只是没有意识到,findFirst()
返回了Optional
。
采纳答案by Andy Turner
Replace get()
with orElse(null)
.
替换get()
为orElse(null)
。
回答by Andrew Tobilko
...findFirst().orElse(null);
Returns the value if present, otherwise returns null
. The documentation saysthat the passed parameter may be null
(what is forbidden for orElseGet
and orElseThrow
).
如果存在则返回值,否则返回null
。文档说传递的参数可能是null
(orElseGet
和禁止的内容orElseThrow
)。
回答by Yakup Ad
my solution was to check it this way
我的解决方案是这样检查
if(item.isPresent()){
item.get().setId("1q2w3e4r5t6y")
}
回答by Erwin Smout
Optional was created so code could after all these decades, finally start avoidingnull.
Optional 的创建是为了让代码经过几十年的发展,最终开始避免null。
Remove the .get(), return the Optional itself and make the calling code deal with it appropriately (just as it would have to do in the case you'd be returning null).
删除 .get(),返回 Optional 本身并使调用代码适当地处理它(就像在返回 null 的情况下必须做的那样)。