【发布时间】:2019-07-19 13:23:15
【问题描述】:
我了解您无法从 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 一定有更简洁的方式。
【问题讨论】:
-
使用
map:return mightReturnAsString().map("something"::equals); -
你为什么不只使用谓词?
-
欢迎发布示例或指向现有问题的链接,以说明您的意思。