Stream of boolean values, is any true?

S1lentSt0rm picture S1lentSt0rm · Oct 10, 2014 · Viewed 52.8k times · Source

I want to parallelize the following code snipped using a 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))

Answer

Marko Topolnik picture Marko Topolnik · Oct 10, 2014

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

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.