Java 10 ifPresentOrElse 返回布尔值

Tyv*_*ain 5 java lambda java-10 option-type

我对“如何正确执行此操作”有点困惑:

 // 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)

Nam*_*man 5

处理布尔返回类型(很容易推断Predicate),一种方法是使用Optional.filter

boolean isValid(Optional<File> optFile) {
    return optFile.filter(this::isZeroLine).isPresent();
}
Run Code Online (Sandbox Code Playgroud)

但是,使用Optionals 参数似乎是一种糟糕的做法。正如卡洛斯的评论中所建议的,另一种实现方式可能是:

boolean isValid(File optFile) {
    return Optional.ofNullable(optFile).map(this::isZeroLine).orElse(false);
}
Run Code Online (Sandbox Code Playgroud)

另一方面,ifPresentOrElse是在执行与值的存在相对应的某些操作时使用的构造,Optional例如:

optFile.ifPresentOrElse(this::doWork, this::doNothing)
Run Code Online (Sandbox Code Playgroud)

相应的操作可以是 -

private void doWork(File f){
     // do some work with the file
}

private void doNothing() {
     // do some other actions
}
Run Code Online (Sandbox Code Playgroud)