Java 布尔值流,是真的吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26304858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:10:12  来源:igfitidea点击:

Stream of boolean values, is any true?

javalambdaparallel-processingjava-8java-stream

提问by S1lentSt0rm

I want to parallelize the following code snipped using a parallelStream:

我想并行化使用parallelStream截取的以下代码:

boolean anyTrue() {
  for (Element e : setOfE) {
    if (eval(e)) {
      return true;
    }
  }
  return false;
}

Will the following work on parallel streams and use regular short-circuit evaluation?

以下是否适用于并行流并使用常规短路评估?

setOfE.parallelStream().map(e -> eval(e)).reduce(false, (a,b) -> a || b))

采纳答案by Marko Topolnik

Streams API actually has first-class support for your requirement:

Streams API 实际上为您的需求提供一流的支持:

setOfE.parallelStream().anyMatch(e->eval(e));

As opposed to your approach with reduce, this is guaranteed to have short-circuit evaluation and optimally leverage parallelism.

与您使用 的方法相反reduce,这可以保证进行短路评估并最佳地利用并行性。

回答by Holger

No, reduction does not support short-circuit evaluation. The reason is that reducejust receives an arbitrary BinaryOperatorimplementation and has no idea about the possibilities of short-circuiting the particular operation.

不,减少不支持短路评估。原因是reduce只接收一个任意的BinaryOperator实现并且不知道短路特定操作的可能性。

But you can perform the entire operation much simpler:

但是您可以更简单地执行整个操作:

setOfE.parallelStream().filter(e -> eval(e)).findAny().isPresent()

This simply searches for an arbitrary item for which evalreturns trueand findAnyallows to end the operation as soon as one thread has encountered a match. The resulting Optionalcan be queried for being empty as you are not interested in the particular matching Element.

这只是搜索eval返回的任意项目,truefindAny允许在一个线程遇到匹配时立即结束操作。Optional由于您对特定匹配不感兴趣,因此可以查询结果是否为空Element

Alternatively you can use as suggested by Marko Topolnik's comment:

或者,您可以按照 Marko Topolnik 评论的建议使用:

setOfE.parallelStream().anyMatch(e -> eval(e))