我知道你不能从 ifPresent()
返回所以这个例子不起作用:
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()
可以返回有效字符串或空可选。我所做的工作是:
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 的更简洁的方法。
最佳答案
我想你要找的只是过滤器
然后检查是否存在:
return result.filter(a -> a.equals("something")).isPresent();
关于java - 从 Java Optional ifPresent() 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54878076/