-1

I have the following test:

@Test
void verifyCorrectLimitForGroups() throws SQLException {
    AbstractDAO<StudentModel, Long> studentsDAO = new StudentDAO(myDatasource);
    List<StudentModel> students = studentsDAO.findAll();
    for(int a=1;a<11;a++) {
        assertTrue(students.stream().filter(i->i.getGroupID()==a).count()<30);
    }
}

My goal is to test if the limit of 30 for students with groupIDs from 1 to 10 was never exceeded. For this purpose, I decided to use java 8 API streams and a simple for loop. Unfortunately, I get a compilation problem: Local variable a defined in an enclosing scope must be final or effectively final. Does it mean I can not do it in this way and I should find a different approach?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 2
    Does this answer your question? [Local variable log defined in an enclosing scope must be final or effectively final](https://stackoverflow.com/questions/38402493/local-variable-log-defined-in-an-enclosing-scope-must-be-final-or-effectively-fi) – flaxel Nov 21 '20 at 22:08

1 Answers1

2

As the error says, variables used inside a lambda expression need to be "final or effectively final", and a is clearly mutable. One possible solution could be to create a dummy variable that's redefined every iteration of the loop to take a's value, but thus isn't mutated:

for (int a = 1; a < 11; a++) {
    int x = a; // Effectively final
    assertTrue(students.stream().filter(i -> i.getGroupID() == x).count() < 30);
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350