Java 8 可选:ifPresent 返回对象 orElseThrow 异常 [英] Java 8 optional: ifPresent return object orElseThrow exception
问题描述
我正在尝试做这样的事情:
I'm trying to make something like this:
private String getStringIfObjectIsPresent(Optional<Object> object){
object.ifPresent(() ->{
String result = "result";
//some logic with result and return it
return result;
}).orElseThrow(MyCustomException::new);
}
这行不通,因为ifPresent 将Consumer 功能接口作为参数,它具有void accept(T t).它不能返回任何值.还有其他方法吗?
This won't work, because ifPresent takes Consumer functional interface as parameter, which has void accept(T t). It cannot return any value. Is there any other way to do it ?
推荐答案
其实你要搜索的是:Optional.map.您的代码将如下所示:
Actually what you are searching is: Optional.map. Your code would then look like:
object.map(o -> "result" /* or your function */)
.orElseThrow(MyCustomException::new);
如果可以,我宁愿省略传递Optional
.最后,您在这里使用 Optional
一无所获.一个稍微不同的变体:
I would rather omit passing the Optional
if you can. In the end you gain nothing using an Optional
here. A slightly other variant:
public String getString(Object yourObject) {
if (Objects.isNull(yourObject)) { // or use requireNonNull instead if NullPointerException suffices
throw new MyCustomException();
}
String result = ...
// your string mapping function
return result;
}
如果您已经有了 Optional
-object 由于另一个调用,我仍然建议您使用 map
-method,而不是 isPresent
等,原因只有一个,我觉得它更具可读性(显然是一个主观决定;-)).
If you already have the Optional
-object due to another call, I would still recommend you to use the map
-method, instead of isPresent
, etc. for the single reason, that I find it more readable (clearly a subjective decision ;-)).
这篇关于Java 8 可选:ifPresent 返回对象 orElseThrow 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!