Reputation: 1646
I've created the following function:
private BooleanExpression createExpresionByJoiningOf(List<BooleanExpression> expresionsForEachStatus) {
BooleanExpression inAnyOfSelectedStatus = expresionsForEachStatus.get(0);
for (int i = 1; i < expresionsForEachStatus.size(); i++) {
inAnyOfSelectedStatus = inAnyOfSelectedStatus.or(expresionsForEachStatus.get(i));
}
return inAnyOfSelectedStatus;
}
The booleanExpression list that it is being pass to the method have been created by stream function:
List<BooleanExpression> expresionsForEachStatus = originalList.stream()
.map(statusToBoleanExpresion)
.collect(Collectors.toList());
My question is how would you create a custom Collector to join the BooleanExpressions of that list. So, I would have something like this:
originalList.stream()
.map(statusToBoleanExpresion)
.collect(joinedBooleanExpresion());
Upvotes: 2
Views: 411
Reputation: 45319
In addition to the good solution posted by Naman, you can skip the full reduction by using anyMatch
, as (it seems to me) the logic of createExpresionByJoiningOf
is to return true
if any of the expressions is truthy:
boolean anyTrue = originalList.stream()
.map(statusToBoleanExpresion)
.anyMatch(exp -> exp.getValue()); //replace with right getter
This avoids the unnecessary iterations that your for-loop (or reduce
) goes over after a true
values has been found
Upvotes: 1
Reputation: 31888
You can declare a method that returns an identity
implementation of BooleanExpression
for the or
operation and then simply perform a reduce
such as:
return expresionsForEachStatus.stream()
.reduce(BooleanExpression.identity(), BooleanExpression::or);
Upvotes: 2