P. Savrov P. Savrov - 5 months ago 12x
Java Question

How to apply a logical operator to all elements in Java

I need to apply the

(logical and) operator to all elements in the list. The problem is: In my current solution, I need to initialize the
variable, and I think the result may become invalid because of the variable having an initial value.

ArrayList<Boolean> results = new ArrayList<>();
for (i = 1; i < results.size(); i++) {
rowResult = rowResult && results.get(i);


As already noted by Jon Skeet or CherryDT you can initialize your rowResult with true. Then your code could look like:

boolean rowResult = true;
for (Boolean el: list) {
    rowResult = el && rowResult;

In case one would like to use operatorOR - || the initial value should be set to false and operator to ||.

In Java 8 you can apply use reduce method for streams:

List<Boolean> list = new ArrayList<>();
boolean rowResult = list.stream().reduce((a,b)-> a && b).orElse(true);

The latter has this advantage that you can apply any logical operator instead of &&.

In the java 8 example one can just change the operator to e.g || to apply OR. The value in orElse statement is just for the case when list is empty.