17

如何在 Java 中编写以下 python 行?

a = [True, False]
any (a)
all (a)

inb4 “你试过什么?”

大锤的方式是编写我自己的allany方法(显然是一个托管它们的类):

public boolean any (boolean [] items)
{
    for (boolean item: items)
        if (item) return true;
    return false;
}

//other way round for all

但我不打算重新发明轮子,必须有一个巧妙的方法来做到这一点......

4

3 回答 3

12

any()和 是一样的Collection#contains(),它标准库的一部分,实际上是所有Collection实现的实例方法。

但是,没有内置的all(). 除了您的“大锤”方法之外,您将获得的最接近的是Google Guava 的 Iterables#all().

于 2013-09-22T04:18:38.440 回答
9

在 Java 7 和更早的版本中,标准库中没有任何东西可以做到这一点。

在 Java 8 中,您应该能够使用Stream.allMatch(...)orStream.anyMatch(...)来做这种事情,尽管我不确定从性能角度来看这是否合理。(首先,您需要使用Boolean而不是boolean...)

于 2013-09-22T04:27:49.247 回答
9

Java 8 流 API 的示例是:

Boolean[] items = ...;
List<Boolean> itemsList = Arrays.asList(items);
if (itemsList.stream().allMatch(e -> e)) {
    // all
}
if (itemsList.stream().anyMatch(e -> e)) {
    // any
}

第三方库的解决方案hamcrest

import static org.hamcrest.Matchers.everyItem;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.is;

if (everyItem(is(true)).matches(itemsList)) {
    // all
}
if (hasItem(is(true)).matches(itemsList)) { // here is() can be omitted
    // any
}
于 2015-09-19T16:12:00.030 回答