是否有任何标准库中的辅助类可以对布尔集合实现逻辑操作?
我编写了这个小助手类,并想知道是否可以从任何地方窃取它,而不是重新实现轮子:
public class Booleans3 {
private Booleans3(){}
public static boolean and(Iterable<Boolean> booleans) {
boolean result = true;
for (Boolean boolRef : booleans) {
boolean bool = boolRef;
result &= bool;
}
return result;
}
public static boolean or(Iterable<Boolean> booleans) {
boolean result = false;
for (Boolean boolRef : booleans) {
boolean bool = boolRef;
result |= bool;
}
return result;
}
}
我查看了 com.google.common.primitives.Booleans,它似乎不包含我需要什么。
I concocted this little helper class, and wanted to know if there's anywhere I can steal it from instead of re-implementing the wheel:
public class Booleans3 {
private Booleans3(){}
public static boolean and(Iterable<Boolean> booleans) {
boolean result = true;
for (Boolean boolRef : booleans) {
boolean bool = boolRef;
result &= bool;
}
return result;
}
public static boolean or(Iterable<Boolean> booleans) {
boolean result = false;
for (Boolean boolRef : booleans) {
boolean bool = boolRef;
result |= bool;
}
return result;
}
}
I looked at com.google.common.primitives.Booleans, and it doesn't seem to contain what I need.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这个怎么样:
How about this:
虽然 @eng-fouad 的答案已经足够好了,但我仍然建议使用另一个 Iterables.all() 和 Iterables.any() 与 equalTo 谓词:
将打印
我看到的优点:
While @eng-fouad answer is good enough I still suggest another one which utilizes Iterables.all() and Iterables.any() with equalTo predicate:
will print
As pluses I see:
我不相信 Java 标准库的任何部分能够提供这种功能。
在某些语言中,它们以称为
anyOf
(对于or
)或allOf
(对于and
)的函数的形式提供。您可能会幸运地搜索实现这些功能的 Java 库。请注意,您这里的代码可以进行相当多的优化。请注意,如果您正在计算许多布尔值的 AND,一旦发现
false
值,您就可以停下来并说答案是false
。同样,如果您正在计算布尔值的 OR,则可以在找到true
值后立即停止,因为答案将为true
。这本质上是短路评估对对象列表的概括,并且是行为一些版本的and
和or
在像Scheme这样的语言中。这给出了以下内容:希望这有帮助!
I don't believe that there is any part of the Java Standard Libraries that provides exactly this functionality.
In some languages, these are provided as functions called
anyOf
(foror
) orallOf
(forand
). You may have some luck searching for Java libraries implementing those functions.A note-, the code you have here can be optimized quite a bit. Note that if you're computing the AND of many boolean values, as soon as you find a
false
value you can stop and say that the answer isfalse
. Similarly, if you're computing the OR of boolean values, you can stop as soon as you find atrue
value, since the answer will betrue
. This is essentially a generalization of short-circuit evaluation to lists of objects, and is the behavior of some versions ofand
andor
in languages like Scheme. This gives the following:Hope this helps!
对 @Eng.Fouad 答案的改进:
如果
boolean
集合为null
或,以下代码返回
,否则对元素进行逻辑运算:false
>emptyAn Improvement on
@Eng.Fouad
answer:The following code return
false
ifboolean
collection isnull
orempty
, otherwise do logical operation on elements: