使用逻辑或而不重复 java 中条件中的变量
Using Logical OR without repeating the variable in the condition in java
有没有办法在java中使用OR而不重复条件中的变量:
例如
if(x != 5 || x != 10 || x != 15)
而是使用类似
的东西
if x not in [5,10,15]
您的第二个示例只是将元素存储在数组中并检查是否存在,在这种情况下不需要 OR。
如果您想走那条路,请将您的元素存储在 List<Integer>
中并使用 contains(Object o)
if(!myList.contains(x))
如果你想排除所有5的乘积,你可以试试这个
if(x % 5 != 0)
您可以在 Java8 流中利用 短路终端操作 (有关详细信息,请参阅 Stream Operations section in the Stream Package Description。)例如:
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);
它产生以下输出:
Bool1: false
Bool2: true
这里有一个比使用 Streams 或 HashMap 的解决方案性能开销小得多的解决方案:
将要检查的值存储在数组中并编写一个小函数来检查 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})) {
...
}
与原始代码相比,开销很小,如果您可以将数组作为常量提取出来,则开销可以忽略不计。
我还发现它比其他解决方案更好读,但这是一个非常主观的意见 ;-)
有没有办法在java中使用OR而不重复条件中的变量:
例如
if(x != 5 || x != 10 || x != 15)
而是使用类似
的东西if x not in [5,10,15]
您的第二个示例只是将元素存储在数组中并检查是否存在,在这种情况下不需要 OR。
如果您想走那条路,请将您的元素存储在 List<Integer>
中并使用 contains(Object o)
if(!myList.contains(x))
如果你想排除所有5的乘积,你可以试试这个
if(x % 5 != 0)
您可以在 Java8 流中利用 短路终端操作 (有关详细信息,请参阅 Stream Operations section in the Stream Package Description。)例如:
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);
它产生以下输出:
Bool1: false
Bool2: true
这里有一个比使用 Streams 或 HashMap 的解决方案性能开销小得多的解决方案:
将要检查的值存储在数组中并编写一个小函数来检查 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})) {
...
}
与原始代码相比,开销很小,如果您可以将数组作为常量提取出来,则开销可以忽略不计。 我还发现它比其他解决方案更好读,但这是一个非常主观的意见 ;-)