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

Publié le: 30 novembre 2022
sur la chaîne: smashplus
920
4

I want to limit the number of values in an ArrayList in the below code

newExam.getQuestionList().stream().forEach(qtn- >{
String title=qtn.getOption1();
if(qtn.getCorrectOptionIndex()==2){
title=qtn.getOption2();
}else if(qtn.getCorrectOptionIndex()==3){
title=qtn.getOption3();
}


dragDropEntities.add(new DragDropEntity(qtn.getId().getQtnId(), title, qtn.getImage()));



I decided to use this way,

int i = 0;
list.stream.forEach(item -> {
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();
newExam.getQuestionList().stream().forEach(qtn->{
String title=qtn.getOption1();
if(qtn.getCorrectOptionIndex()==2){
title=qtn.getOption2();
}else if(qtn.getCorrectOptionIndex()==3){
title=qtn.getOption3();
}
if(atomicInteger.getAndIncrement()<6) {
dragDropEntities.add(new DragDropEntity(qtn.getId().getQtnId(), title, qtn.getImage()));
}


}
);
This solves the issue and I can see the list correctly with six elements


Sur cette page du site, vous pouvez voir la vidéo en ligne How to resolve Variable in lambda expression should be final or effectively final in forEach Java 8 durée heure minute seconde en bonne qualité , qui a été Téléchargé par l'utilisateur smashplus 30 novembre 2022, Partagez le lien avec vos amis et connaissances, sur youtube cette vidéo a déjà été regardée 920 fois et il a aimé 4 téléspectateurs. Bon visionnage!