我对“如何正确执行此操作”感到困惑:
// 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;
}
我知道语法不正确且无法编译,但这仅是您了解的主意。
如何将其转换为“干净的代码”? 即避免这样做:
if (optFile.isPresent()) {//} else {//}
答案 0 :(得分:3)
使用布尔返回类型(很容易推断出Predicate
s),一种实现方法是使用Optional.filter
:
boolean isValid(Optional<File> optFile) {
return optFile.filter(this::isZeroLine).isPresent();
}
但是,然后使用Optional
的参数似乎是一种不好的做法。正如卡洛斯(Carlos)的评论所建议的那样,另一种实现方式可能是:
boolean isValid(File optFile) {
return Optional.ofNullable(optFile).map(this::isZeroLine).orElse(false);
}
另一方面,ifPresentOrElse
是一种结构,用于执行与Optional
值的存在相对应的某些操作,例如:
optFile.ifPresentOrElse(this::doWork, this::doNothing)
相应的动作可能是-
private void doWork(File f){
// do some work with the file
}
private void doNothing() {
// do some other actions
}