1

Following is My Code

List<Lead> Mylead = adminService.GetMyData(10);
int i=0;
Mylead.forEach(lead->{
  i++;
});

Error : Local variable I defined in an enclosing scope must be final or effectively final

Sajan Parmar
  • 85
  • 1
  • 10
  • make it `final`, but what's the detailed use case? – Naman Nov 15 '17 at 05:54
  • 1
    why you want to change value inside the for loop , and with a constant literal? add some more details in your question – Shankar Nov 15 '17 at 05:55
  • Related questions: [Java 8 Lambda variable scope](https://stackoverflow.com/q/40862845/8097737) and [why variables inside foreach loop of java8 should be final?](https://stackoverflow.com/q/31801313/8097737) –  Nov 15 '17 at 06:52
  • The language has been designed to make stupid things harder. Just write `int i = Mylead.size();` instead. – Holger Nov 15 '17 at 11:44

1 Answers1

2

You have to create a wrapper for i, a simple way to do this would be an array.

List<Lead> Mylead = adminService.GetMyData(10);
final int[] i={0};
Mylead.forEach(lead->{
  i[0]++;
});

For a detailed explanation how this works see: Java 8 Lambda variable scope

  • I want to increment variable i Here is my code : List Mylead = adminService.GetMyData(10); int i=0; Mylead.forEach(lead->{ i++; }); – Sajan Parmar Nov 15 '17 at 06:30
  • Thanks.It's Work for me.But What is the problem With My Code.Any Reason?Why should Variable "i" is not accessed? – Sajan Parmar Nov 15 '17 at 06:41
  • @RahulParmar Because lambdas and state don't mix well. Use a normal for loop instead. – shmosel Nov 15 '17 at 06:46