Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream of boolean values, is any true?

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))
like image 879
S1lentSt0rm Avatar asked Oct 20 '22 09:10

S1lentSt0rm


People also ask

What is the value of Boolean true?

Boolean values and operationsConstant true is 1 and constant false is 0. It is considered good practice, though, to write true and false in your program for boolean values rather than 1 and 0. The following table shows comparisons and boolean operations.

Is Boolean true or true?

The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true" . Example: Boolean.

Are booleans always true?

In the boolean type, there are only two possible values: true and false. We can have variables and expressions of type boolean, just has we have variables and expressions of type int and double. A boolean variable is only capable of storing either the value true or the value false.

What is true of a stream in Java?

Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.


2 Answers

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.

like image 126
Marko Topolnik Avatar answered Oct 21 '22 23:10

Marko Topolnik


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

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 eval returns true and findAny allows to end the operation as soon as one thread has encountered a match. The resulting Optional can be queried for being empty as you are not interested in the particular matching Element.

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

setOfE.parallelStream().anyMatch(e -> eval(e))
like image 24
Holger Avatar answered Oct 21 '22 22:10

Holger