Rajitha Bhanuka
Rajitha Bhanuka

Reputation: 842

Is there way to change a value inside in Lambda Expression?

I want to change the feeAmount and message, Using for loop I did, but I want to use Lambda (by default all variable are final in Lambda).

        gridFeeEntity.stream().forEach(entity -> {
        if ("T".equals(entity.getType())){

            feeAmount += 1;

        }else if ("P".equals(entity.getType())) {

            feeAmount += 2;

        } else {
            message = "not Supported";
        }
    });

Upvotes: 0

Views: 161

Answers (2)

In addition to Tim's answer, I would suggest considering inverting your logic. (Note that your "message" bit should almost certainly be an exception.)

int feeIncrease = gridFeeEntities.stream()
  .map(GridFeeEntity::getType)
  .mapToInt(FeeList::forType)
  .sum();

feeAmount += feeIncrease;

Upvotes: 6

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521457

Streams are not ideal for every use case, and I actually would prefer using a plain enhanced for loop here:

for (GridFeeEntity entity : gridFeeEntity) {
    if ("T".equals(entity.getType())) {
        feeAmount += 1;
    }
    else if ("P".equals(entity.getType())) {
        feeAmount += 2;
    }
    else {
        message = "not Supported";
    }
}

This is clean, easy to read, and should still perform about as well as stream, especially for smaller collections.

Upvotes: 3

Related Questions