我想做这样的事情:
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).它不能返回任何值.还有其他办法吗?
1/ 工作代码:
public Student process (int id, name){
Optional<Student> studentOpt = myrepo.findById(id);
studentOpt.isPresent() {
return updateStudent(id, name);
} else {
return createStudent(id, name);
}
Run Code Online (Sandbox Code Playgroud)
2/ 我尝试将其更改为“完整的 lambdas 代码”(不起作用):
public Student process (int id, name){
Optional<Student> studentOpt = myrepo.findById(id);
return studentOpt.ifPresentOrElse(student-> return updateStudent(id, name), () -> return createStudent(id, name));
}
Run Code Online (Sandbox Code Playgroud)
1/ 我应该将其更改为完整的 lambda 吗?什么是最干净的?
2/ 如果是,如何?
我对“如何正确执行此操作”有点困惑:
// return true: if present and number of lines != 0
boolean isValid(Optional<File> optFile) {
return optFile.ifPresentOrElse(f -> return !isZeroLine(f), return false);
}
private boolean isZeroLine(File f) {
return MyFileUtils.getNbLinesByFile(f) == 0;
}
Run Code Online (Sandbox Code Playgroud)
我知道语法不正确并且无法编译,但这只是为了让您了解这个想法。
我怎样才能把它变成“干净的代码”?即避免这样做:
if (optFile.isPresent()) {//} else {//}
Run Code Online (Sandbox Code Playgroud)