Java 10 ifPresentOrElse that return boolean

a 夏天 提交于 2021-02-07 19:53:12

问题


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

回答1:


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
}


来源:https://stackoverflow.com/questions/52617309/java-10-ifpresentorelse-that-return-boolean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!