1

I want to update the amount value, but it need to be final

int amount = 0;

// update value somewhere
amount = 12;

txs.forEach(p -> {
    p.setAmount(amount);
});

How to update all the txs with the same value?

4
  • Put it into the effectively final variable. Commented Jul 12, 2021 at 9:08
  • 2
    does this compile?? int amount 0; Commented Jul 12, 2021 at 9:09
  • Do you need the amount variable to be final? If no then explain a bit more. When a final variable is declared and assigned its value cannot be changed. So first declare the variable as final int amount; and do not assign any value. Assign at a place where you need. Or declare and assign at class level as a static constant. It all depends on your requirement. Commented Jul 12, 2021 at 9:18
  • You need to provide more context. You could simply write int amount = 12 in the first place, but I think you are already aware of that. So you need to show us where and how exactly you are planning to update the amount variable. Commented Jul 12, 2021 at 9:53

2 Answers 2

3

You can do it like this

int amount = 0;

// update value somewhere
amount = 12;

  // add this
final int final_amount = amount ;

txs.forEach(p -> {
    p.setAmount(final_amount);
});
Sign up to request clarification or add additional context in comments.

Comments

2

An easy way to do it: Create a temporary variable like that:

int amount = 0;

// update value somewhere
amount = 12;

final int myFinalVariable = amount;

txs.forEach(p -> p.setAmount(myFinalVariable));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.