Java 10 ifPresentOrElse that return boolean

Tyvain :

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'? i.e. avoid doing:

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

Dealing with boolean return type(easily inferred Predicates), 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 Optionals 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
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=99719&siteId=1