Is there a simpler way to check multiple values against one value in an if-statement?

前端 未结 12 923
名媛妹妹
名媛妹妹 2020-11-27 07:55

Basically, what I want to do is check two integers against a given value, therefore, classically what you would do is something like this:

//just to get some         


        
12条回答
  •  佛祖请我去吃肉
    2020-11-27 08:13

    In Java 8 we can achieve the same by using the below method:

    private boolean methodName(int variant,int... args){
            if(args.length > 0){ return Arrays.stream(args).anyMatch( x -> x == variant); }
            return false;
        }
    

    The given method will return true if the variant will match any possible input(s). This is used for or condition.

    In the same way, if you want to do &&(and) condition then you just need to used other Java 8 methods:

    Note: These methods take Predicate as an argument.

    anyMatch: return true the moment the first predicate returns true otherwise false.

    allMatch: return true if all the predicates return true otherwise false.

    noneMatch: return true if none of the predicates return true otherwise false.

    Performance Note: This is good when you have enough amount of data to check as it has some overhead but it works really well when you use this for enough amount of data. normal way is good for just two conditions.

提交回复
热议问题