我对“如何正确地做到这一点”有点困惑:
// 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 {//}
处理布尔返回类型(易于推断 Predicate s) ,一种方法是 Optional.filter
Predicate
Optional.filter
boolean isValid(Optional<File> optFile) { return optFile.filter(this::isZeroLine).isPresent(); }
但是,使用 Optional
Optional
boolean isValid(File optFile) { return Optional.ofNullable(optFile).map(this::isZeroLine).orElse(false); }
ifPresentOrElse 是在执行与 可选
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 }