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))
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.