简体   繁体   中英

Using Logical OR without repeating the variable in the condition in java

Is there a way of using OR in java without repeating the variable in the condition:

For example

if(x != 5 || x != 10 || x != 15)

instead use something like

if x not in [5,10,15]

You can take advantage of short-circuit terminal operations in Java8 streams (See the Stream Operations section in the Stream Package Description for details.) For example:

int x = 2;

// OR operator
boolean bool1 = Stream.of(5, 10, 15).anyMatch(i -> i == x);
System.out.println("Bool1: " +bool1);

// AND operator
boolean bool2 = Stream.of(5, 10, 15).allMatch(i -> i != x);
System.out.println("Bool2: " +bool2);

It produces the following output:

Bool1: false
Bool2: true

Your second example is just storing elements in an array and checking for existence, no need for OR in that case.

If you want to go that route, store your elements in a List<Integer> and use contains(Object o)

if(!myList.contains(x))

如果要排除所有5的乘法,可以尝试一下

if(x % 5 != 0)

Here a solution that comes with much less performance overhead than the ones using Streams or a HashMap:

Store the values you want to check against in an array and write a small function to check whether x is among these values

private static boolean isNotIn(int x, int[] values) {
    for (int i : values) {
        if (i == x) {
            return false;
        }
    }
    return true;
}



if (isNotIn(x, new int[] {5, 10, 15})) {
  ...
}

The overhead is minimal compared to the original code and becomes negligible if you can pull out the array as a constant. I also find that it is nicer to read than the other solutions but that is a very subjective opinion ;-)

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