filmov
tv
How to resolve Variable in lambda expression should be final or effectively final in forEach Java 8

Показать описание
I want to limit the number of values in an ArrayList in the below code
}
I decided to use this way,
int i = 0;
i++;
});
but this gives me the error "Variable used in lambda expression should be final or effectively final"
Because this variable I is incrementing inside lambda expression it is not final so this gives the above error.
So I fixed this by using the AtomicInteger in the below way,
AtomicInteger atomicInteger=new AtomicInteger();
}
}
}
);
This solves the issue and I can see the list correctly with six elements
}
I decided to use this way,
int i = 0;
i++;
});
but this gives me the error "Variable used in lambda expression should be final or effectively final"
Because this variable I is incrementing inside lambda expression it is not final so this gives the above error.
So I fixed this by using the AtomicInteger in the below way,
AtomicInteger atomicInteger=new AtomicInteger();
}
}
}
);
This solves the issue and I can see the list correctly with six elements