Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 rowResult 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);
}
like image 743
P. Savrov Avatar asked Dec 01 '22 13:12

P. Savrov


2 Answers

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.

like image 163
Dawid Wysakowicz Avatar answered Dec 05 '22 06:12

Dawid Wysakowicz


In Java 8, you can use streams:

boolean rowResult = results.stream().allMatch(b -> b);

Before Java 8, there was Guava:

boolean rowResult = Iterables.all(results, new Predicate<Boolean>() {
    @Override
    public boolean apply(Boolean input) {
        return input;
    }
});
like image 34
Mifeet Avatar answered Dec 05 '22 07:12

Mifeet