简体   繁体   English

使用逻辑或而不重复Java条件中的变量

[英]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: 有没有一种方法可以在Java中使用OR而不在条件中重复变量:

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: 您可以利用Java8流中的短路端子操作 (有关详细信息,请参见“流程序包描述”中的流操作”部分 。)例如:

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. 您的第二个示例只是将元素存储在数组中并检查是否存在,在这种情况下不需要OR。

If you want to go that route, store your elements in a List<Integer> and use contains(Object o) 如果要走那条路线,请将元素存储在List<Integer>并使用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: 这里的解决方案比使用Streams或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 将要检查的值存储在数组中,并编写一个小函数以检查x是否在这些值中

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 ;-) 我还发现阅读起来比其他解决方案更好,但这是一个非常主观的观点;-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM