'Local variable collect defined in an enclosing scope must be final or effectively final

I'm getting an error Local variable collect defined in an enclosing scope must be final or effectively final at collect. I tried declaring the collect at class level surrouning with final but still I'm getting same error.

Any help is appreciated. Thanks!!

my code

@Override
    public List<FinalAssessment> getFactorsChild(String pid) {
        
        //probationer fa performance 
        List<FinalAssessment> probationerFa = faAssessment.getProbationerFa(pid);
        
        //master factors
        List<FinalAssessment> factorsChild = faAssessment.getFactorsChild();
        /*
         * Setting marked performance grades to the factorschild list to show marked
         * performance grades in list
         */ 
        
        probationerFa.forEach(fa-> {
            if(fa.getGradecode()!=null) {
                collect = factorsChild.stream().
                filter(l->l.getGradecode().equals(fa.getItemcode())).
                peek(pfa-> pfa.setGradecode(fa.getGradecode())).collect(Collectors.toList());
            }
        });
        
        collect.forEach( x-> System.out.println("G code " + x.getGradecode()));
        
        return faAssessment.getFactorsChild();
    }



Solution 1:[1]

Inside lambda function all variable have to be final.

you can create your collect variable as Atomic and then you can assign on it your list:

 AtomicReference<List<FinalAssessment>> collect = null;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fabio19933