简体   繁体   中英

Java 10 ifPresentOrElse that return boolean

I am a little confused on "how to do this properly":

 // 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 know the syntax is not correct and not compiling, but it's just for you to get the idea.

How can I turn this into 'clean code'? ie avoid doing:

if (optFile.isPresent()) {//} else {//}

Dealing with boolean return type(easily inferred Predicate s), one way to do that could be to use Optional.filter :

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

But, then using Optional s arguments seems to be a poor practice. As suggested in comments by Carlos as well, another way of implementing it could possibly be:

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

On another note, ifPresentOrElse is a construct to be used while performing some actions corresponding to the presence of the Optional value something like :

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

where the corresponding actions could be -

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM