gpt4 book ai didi

返回 boolean 值的 Java 10 ifPresentOrElse

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:32:04 24 4
gpt4 key购买 nike

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

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

最佳答案

处理 boolean 返回类型(很容易推断出 Predicate),一种方法是使用 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)

相应的 Action 可能在哪里 -

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

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

关于返回 boolean 值的 Java 10 ifPresentOrElse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52617309/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com