Java8可选:ifPresent返回对象或lsethorn异常
我正试着做这样的事情:Java8可选:ifPresent返回对象或lsethorn异常,java,lambda,optional,Java,Lambda,Optional,我正试着做这样的事情: private String getStringIfObjectIsPresent(Optional<Object> object){ object.ifPresent(() ->{ String result = "result"; //some logic with result and return it return result; }).o
private String getStringIfObjectIsPresent(Optional<Object> object){
object.ifPresent(() ->{
String result = "result";
//some logic with result and return it
return result;
}).orElseThrow(MyCustomException::new);
}
私有字符串GetStringIfObjectsPresent(可选对象){
对象。如果存在(()->{
String result=“result”;
//带结果的一些逻辑并返回它
返回结果;
}).orelsetrow(MyCustomException::new);
}
这将不起作用,因为ifPresent将使用者函数接口作为参数,它具有void accept(t)。它不能返回任何值。还有其他方法吗?请改用
map
-功能。它将转换可选文件中的值
像这样:
private String getStringIfObjectIsPresent(Optional<Object> object) {
return object.map(() -> {
String result = "result";
//some logic with result and return it
return result;
}).orElseThrow(MyCustomException::new);
}
私有字符串GetStringIfObjectsPresent(可选对象){
返回object.map(()->{
String result=“result”;
//带结果的一些逻辑并返回它
返回结果;
}).orelsetrow(MyCustomException::new);
}
实际上,您正在搜索的是:。您的代码将如下所示:
object.map(o -> "result" /* or your function */)
.orElseThrow(MyCustomException::new);
如果可以的话,我宁愿省略传递可选的。最后,在这里使用可选的,您将一无所获。另一个稍微不同的变体:
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;
}
如果由于另一个调用,您已经有了可选对象
,我仍然建议您使用映射
-方法,而不是isPresent
,因为我发现它更可读(显然是主观决定;-)。这里有两个选项:
用map
替换ifPresent
,并使用功能
代替消费者
private String getStringIfObjectIsPresent(Optional<Object> object) {
return object
.map(obj -> {
String result = "result";
//some logic with result and return it
return result;
})
.orElseThrow(MyCustomException::new);
}
我更喜欢在确保值可用后进行映射
private String getStringIfObjectIsPresent(Optional<Object> object) {
Object ob = object.orElseThrow(MyCustomException::new);
// do your mapping with ob
String result = your-map-function(ob);
return result;
}
私有字符串GetStringIfObjectsPresent(可选对象){
Object ob=Object.orelsetrow(MyCustomException::new);
//使用ob进行映射
字符串结果=映射函数(ob);
返回结果;
}
还是一艘班轮
private String getStringIfObjectIsPresent(Optional<Object> object) {
return your-map-function(object.orElseThrow(MyCustomException::new));
}
私有字符串GetStringIfObjectsPresent(可选对象){
返回映射函数(object.orelsethorn(MyCustomException::new));
}
可能的重复注意,第二个选项不是推荐的使用选项的方法。map
不适用于此用途。它总是有一个返回类型,所以最好执行returnsomeoptional.orelsetrow(()->…)代码>--不清楚OP是否打算返回某些内容。
private String getStringIfObjectIsPresent(Optional<Object> object) {
return your-map-function(object.orElseThrow(MyCustomException::new));
}