代码之家  ›  专栏  ›  技术社区  ›  Tyvain

返回布尔值的Java10ifPresentRelse

  •  3
  • Tyvain  · 技术社区  · 6 年前

    我对“如何正确地做到这一点”有点困惑:

     // 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;
     }
    

    i、 e.避免:

    if (optFile.isPresent()) {//} else {//}
    
    1 回复  |  直到 6 年前
        1
  •  4
  •   Naman    6 年前

    处理布尔返回类型(易于推断 Predicate s) ,一种方法是 Optional.filter

    boolean isValid(Optional<File> optFile) {
        return optFile.filter(this::isZeroLine).isPresent();
    }
    

    但是,使用 Optional

    boolean isValid(File optFile) {
        return Optional.ofNullable(optFile).map(this::isZeroLine).orElse(false);
    }
    

    ifPresentOrElse 是在执行与 可选

    optFile.ifPresentOrElse(this::doWork, this::doNothing)
    

    相应的行动可能是-

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