返回布尔值的Java 10 IfPresentOverse

返回布尔值的Java 10 IfPresentOverse,java,lambda,optional,java-10,Java,Lambda,Optional,Java 10,我对“如何正确地做到这一点”有点困惑: 处理布尔返回类型(易于推断的谓词s),一种方法是使用: 另一个注意事项是,ifpresentorese是在执行与可选值的存在对应的一些操作时使用的一个构造,例如: optFile.ifPresentOrElse(this::doWork, this::doNothing) 如果相应的行动可能是—— private void doWork(File f){ // do some work with the file } private voi

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


处理布尔返回类型(易于推断的
谓词
s),一种方法是使用:


另一个注意事项是,
ifpresentorese
是在执行与
可选
值的存在对应的一些操作时使用的一个构造,例如:

optFile.ifPresentOrElse(this::doWork, this::doNothing)
如果相应的行动可能是——

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

private void doNothing() {
     // do some other actions
}

有种
optFile.map(this::isZeroLine).orElse(false)
?但不确定是否有一个可选的作为参数是一个好的选择idea@CarlosHeuberger就这样!阅读Java变得越来越不可能了。@Tyvain两者都是很好的解决方案。如果您有一个
可选的
参数,请不要屈服于()。
boolean isValid(Optional<File> optFile) {
    return optFile.filter(this::isZeroLine).isPresent();
}
boolean isValid(File optFile) {
    return Optional.ofNullable(optFile).map(this::isZeroLine).orElse(false);
}
optFile.ifPresentOrElse(this::doWork, this::doNothing)
private void doWork(File f){
     // do some work with the file
}

private void doNothing() {
     // do some other actions
}