Ric*_*rdK 28 java lambda optional
我想做这样的事情:
private String getStringIfObjectIsPresent(Optional<Object> object){
object.ifPresent(() ->{
String result = "result";
//some logic with result and return it
return result;
}).orElseThrow(MyCustomException::new);
}
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为ifPresent将Consumer功能接口作为参数,其具有void accept(T t).它不能返回任何值.还有其他办法吗?
Rol*_*and 35
实际上你在搜索的是:Optional.map.您的代码将如下所示:
object.map(o -> "result" /* or your function */)
.orElseThrow(MyCustomException::new);
Run Code Online (Sandbox Code Playgroud)
Optional如果可以,我宁愿省略通过.最后你Optional在这里没有任何收获.一个稍微其他的变体:
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;
}
Run Code Online (Sandbox Code Playgroud)
如果你Optional因为另一个电话而已经拥有了-object,我仍然建议你使用map-method,而不是isPresent等等,因为单一的原因,我发现它更具可读性(显然是一个主观的决定;-)).
iam*_*ddy 13
在确定值可用后,我更喜欢映射
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;
}
Run Code Online (Sandbox Code Playgroud)
或一个班轮
private String getStringIfObjectIsPresent(Optional<Object> object) {
return your-map-function(object.orElseThrow(MyCustomException::new));
}
Run Code Online (Sandbox Code Playgroud)
请改用map-function.它会转换可选内部的值.
像这样:
private String getStringIfObjectIsPresent(Optional<Object> object) {
return object.map(() -> {
String result = "result";
//some logic with result and return it
return result;
}).orElseThrow(MyCustomException::new);
}
Run Code Online (Sandbox Code Playgroud)
这里有两个选择:
替换ifPresent为map和使用Function而不是Consumer
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);
}
Run Code Online (Sandbox Code Playgroud)
用途isPresent:
private String getStringIfObjectIsPresent(Optional<Object> object) {
if (object.isPresent()) {
String result = "result";
//some logic with result and return it
return result;
} else {
throw new MyCustomException();
}
}
Run Code Online (Sandbox Code Playgroud)