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);
}
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.
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;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With