Java中与Python all和any相对应的函数

19

我该如何用Java编写以下Python代码?

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

在我还没有开始解释之前,有人可能会问:"你尝试过什么?"

最简单的方法是编写自己的allany方法(当然还需要一个类来承载它们):

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

//other way round for all

但我并不打算重新发明轮子,肯定有一个巧妙的方法来实现这个...

3个回答

13

any()Collection#contains()相同,而后者是标准库的一部分,实际上是所有 Collection 实现的实例方法。

然而,并没有内置的 all() 。 除了你提到的笨拙方法外,最接近的方法是使用 Google GuavaIterables#all()


谢谢。所以在标准库中没有可用的吗? - Hyperboreus
7
我的心充满了悲伤,眼泪涌上了眼眶。谢谢你。正在等待CD接受。 - Hyperboreus
Guava会让Java整体变得更加美好(尤其是在你可以像Java 8中那样使用lambda表达式时)。请熟悉一下。 - Matt Ball
即使没有内置的 all(),您也可以使用 De Morgan 定律轻松获得它。也就是说,all(a) = !any(!a) - Jeff Irwin
5
any() 不同于 Collection#contains()any() 可以接受任何可迭代对象并在迭代过程中遇到真值时返回 True。 这里的关键是在 Python 中通常使用生成器表达式提供可迭代对象;例如:any(path.startswith(prefix) for prefix in collection_of_prefixes)。这使得 any() 对于任意测试非常有用。Collection#contains() 仅支持等值测试。Java 8 流 API 的 anyMatch() 测试是一个很好的相当方法。 - Martijn Pieters
@MartijnPieters 同意。 - Matt Ball

11
在Java 7及更早版本中,标准库中没有可用于此类操作的内容。
在Java 8中,您应该能够使用Stream.allMatch(...)Stream.anyMatch(...)来执行此类操作,尽管我不确定这是否从性能角度来看是有道理的。(首先,您需要使用Boolean而不是boolean...)

谢谢你的回答。让我们看看Java8何时能够到达Dalvik。 - Hyperboreus

10

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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接