user2992476
user2992476

Reputation: 1646

Java Collect Joining Custom Function

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

Answers (2)

ernest_k
ernest_k

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

Naman
Naman

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

Related Questions