从Java返回可选的ifPresent() [英] Returning from Java Optional ifPresent()
本文介绍了从Java返回可选的ifPresent()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道您无法从ifPresent()
返回,因此此示例不起作用:
I understand you can't return from a ifPresent()
so this example does not work:
public boolean checkSomethingIfPresent() {
mightReturnAString().ifPresent((item) -> {
if (item.equals("something")) {
// Do some other stuff like use "something" in API calls
return true; // Does not compile
}
});
return false;
}
mightReturnAString()
可以的地方,返回有效的字符串或空的可选字符.我所做的工作是:
Where mightReturnAString()
could return a valid string or an empty optional. What I have done that works is:
public boolean checkSomethingIsPresent() {
Optional<String> result = mightReturnAString();
if (result.isPresent()) {
String item = result.get();
if (item.equals("something") {
// Do some other stuff like use "something" in API calls
return true;
}
}
return false;
}
,它更长,并且与仅检查空值没有太大区别.我觉得使用Optional必须有更简洁的方法.
which is longer and does not feel much different to just checking for nulls in the first place. I feel like there must be a more succinct way using Optional.
推荐答案
我认为您正在寻找的只是filter
并检查是否存在:
I think all you're looking for is simply filter
and check for the presence then:
return result.filter(a -> a.equals("something")).isPresent();
这篇关于从Java返回可选的ifPresent()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文