检查布尔数组中的所有值是否都为真的最优雅的方法是什么?
我在java中有一个布尔数组:
boolean[] myArray = new boolean[10];
检查所有值是否都为真的最优雅的方法是什么?
I have a boolean array in java:
boolean[] myArray = new boolean[10];
What's the most elegant way to check if all the values are true?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
在 Java 8 中,你可以这样做:
或者更短:
注意:
您需要
Boolean[]
才能使此解决方案发挥作用。因为你不能有一个基元列表。In Java 8, you could do:
Or even shorter:
Note:
You need
Boolean[]
for this solution to work. Because you can't have a primitives List.这取决于您想要查找此信息的次数,如果不止一次:
否则会出现短路循环:
It depends how many times you're going to want to find this information, if more than once:
Otherwise a short circuited loop:
我不敢相信没有
BitSet< /code>
解决方案。
BitSet
是一组位的抽象,因此我们不必再使用boolean[]
进行更高级的交互,因为它已经包含了大多数所需的方法。它在批处理操作中也非常快,因为它内部使用long
值来存储位,因此不会像我们使用boolean[]
那样单独检查每个位。对于您的特定情况,我会使用
cardinality()
:另一种选择是使用 番石榴:
I can't believe there's no
BitSet
solution.A
BitSet
is an abstraction over a set of bits so we don't have to useboolean[]
for more advanced interactions anymore, because it already contains most of the needed methods. It's also pretty fast in batch operations since it internally useslong
values to store the bits and doesn't therefore check every bit separately like we do withboolean[]
.For your particular case, I'd use
cardinality()
:Another alternative is using Guava:
该行应该足够了:
BooleanUtils.and(boolean... array)
但为了让仅链接的纯粹主义者平静下来:
That line should be sufficient:
BooleanUtils.and(boolean... array)
but to calm the link-only purists:
在 Java 8+ 中,您可以在
0
到myArray.length
范围内创建一个IntStream
并检查所有值是否为true
在相应的(原始)数组中,类似于:In Java 8+, you can create an
IntStream
in the range of0
tomyArray.length
and check that all values aretrue
in the corresponding (primitive) array with something like,这可能不会更快,而且绝对不可读。所以,为了丰富多彩的解决方案......
This is probably not faster, and definitely not very readable. So, for the sake of colorful solutions...
我认为这看起来不错并且表现得很好......
I think this looks ok and behaves well...
您可以通过 Arrays.equal 方法将您的数组与其他布尔数组进行比较,检查所有值项是 true 还是 false,如下例所示:
You can check all value items are true or false by compare your array with the other boolean array via
Arrays.equal
method like below example :科特林:
如果一个元素为 false,则不会选择所有元素
Kotlin:
if one elemnt is false then not all are selected
好的。这是我能即时想到的“最优雅”的解决方案:
希望有帮助!
OK. This is the "most elegant" solution I could come up with on the fly:
Hope that helps!