Skip to main content
edited tags
Link
John Saunders
  • 161.9k
  • 26
  • 252
  • 403
added 9 characters in body
Source Link
Dan
  • 9.8k
  • 14
  • 58
  • 71

Given this situation where a lambda is inside a for loop I would expect the counter i to be effectively final.

The compiler complains that i is not effectively final so I had to use i2.

for (int i = 0; i < x.getBooks().size(); i++){
   //The compiler needs i to be effectively final.
   int i2 = i;
   List<Book> books = bookstore.stream()
                    .filter(c -> c.getAuthorgetAuthors().get(i2).equals("xxx"))
                    .collect(Collectors.toList());
}

So the question is why i is not effectively final inside the scope of the for loop and is this the simplest workaround.

Given this situation where a lambda is inside a for loop I would expect the counter i to be effectively final.

The compiler complains that i is not effectively final so I had to use i2.

for (int i = 0; i < x.getBooks().size(); i++){
   //The compiler needs i to be effectively final.
   int i2 = i;
   List<Book> books = bookstore.stream()
                    .filter(c -> c.getAuthor().equals("xxx"))
                    .collect(Collectors.toList());
}

So the question is why i is not effectively final inside the scope of the for loop and is this the simplest workaround.

Given this situation where a lambda is inside a for loop I would expect the counter i to be effectively final.

The compiler complains that i is not effectively final so I had to use i2.

for (int i = 0; i < x.getBooks().size(); i++){
   //The compiler needs i to be effectively final.
   int i2 = i;
   List<Book> books = bookstore.stream()
                    .filter(c -> c.getAuthors().get(i2).equals("xxx"))
                    .collect(Collectors.toList());
}

So the question is why i is not effectively final inside the scope of the for loop and is this the simplest workaround.

Source Link
Dan
  • 9.8k
  • 14
  • 58
  • 71

Java lambda - for loop counter is not effectively final

Given this situation where a lambda is inside a for loop I would expect the counter i to be effectively final.

The compiler complains that i is not effectively final so I had to use i2.

for (int i = 0; i < x.getBooks().size(); i++){
   //The compiler needs i to be effectively final.
   int i2 = i;
   List<Book> books = bookstore.stream()
                    .filter(c -> c.getAuthor().equals("xxx"))
                    .collect(Collectors.toList());
}

So the question is why i is not effectively final inside the scope of the for loop and is this the simplest workaround.