[英]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]
您可以利用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);
它產生以下輸出:
Bool1: false
Bool2: true
您的第二個示例只是將元素存儲在數組中並檢查是否存在,在這種情況下不需要OR。
如果要走那條路線,請將元素存儲在List<Integer>
並使用contains(Object o)
if(!myList.contains(x))
如果要排除所有5的乘法,可以嘗試一下
if(x % 5 != 0)
這里的解決方案比使用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})) {
...
}
與原始代碼相比,開銷很小,如果可以將數組作為常量拉出,則開銷可以忽略不計。 我還發現閱讀起來比其他解決方案更好,但這是一個非常主觀的觀點;-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.