Java 8可选:ifPresent返回对象或ElseThrow异常 [英] 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将消费者功能接口作为参数,其具有无效的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 ?
推荐答案
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
对象,出于单个原因,我仍然建议您使用map
方法而不是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返回对象或ElseThrow异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!