简体   繁体   中英

How can I simplify multiple “||”?

I want to make the if-condition simplify, I really appreciate your advice.

if (StringUtils.isNotBlank(Constant.A)
            || StringUtils.isNotBlank(Constant.B)
            || StringUtils.isNotBlank(Constant.C)
            || StringUtils.isNotBlank(Constant.D)
            || StringUtils.isNotBlank(Constant.E)) {
        return true;
}

You could return directly:

return StringUtils.isNotBlank(Constant.A)
        || StringUtils.isNotBlank(Constant.B)
        || StringUtils.isNotBlank(Constant.C)
        || StringUtils.isNotBlank(Constant.D)
        || StringUtils.isNotBlank(Constant.E);

But besides putting that validations inside a method I don't believe you can simplify more.

If you want to make your condition shorter (but not faster), you can use a stream for this.

if (Stream.of(Constant.A, Constant.B, Constant.C, Constant.D, Constant.E)
          .anyMatch(StringUtils::isNotBlank)) {
    return true;
}

You Could use StringUtils.isAllBlank()

if(!StringUtils.isAllBlank(Constant.A,Constant.B,.......)){
    return true;
}

If a single constant is Not Blank true is returned.

TLDR: this condition cannot be simplified in terms of boolean algebra.

In boolean algebra there is a notion of canonical normal forms . These forms can be useful for the simplification of boolean expressions, which is of great importance in the optimization of boolean formulas in general. There are, basically, two of them: minterms and maxterms. They are actually duals, ie they are functionally equivalent and can be transformed one into other while preserving the truth table.

Let's look at maxterms . For a boolean function of N variables, a sum term in which each of the variables appears once (either in its complemented (negated) or uncomplemented form) is called a maxterm. Thus, a maxterm is a logical expression of N variables that employs only the complement operator and the disjunction operator.

That is exactly your case!

You have all the variables – A , B , C , D and E – used only once in you expression and you used only || operator (which is actually a disjunction). So, your expression is already in it's normal form and cannot be simplified in terms of needed computations.

You can make it shorter (and more scalable if the number of variables grows) by employing collections / streams operations like other answers advise, but not simpler.

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