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
As the other answers mention, effectively final
means, that a variable only can be assigned once and will not be reassigned. That's not the case in a for-loop. effectively final
exists, because otherwise developers have to explicitly mark a variable as final
to use it in a lambda.
However, the reason i'm answering is a solution, to write your code without duplicating i
:
IntStream.range (0, x.getBooks().size()).forEach (i -> {
List books = bookstore.stream()
.filter(c -> c.getAuthors().get(i).equals("xxx"))
.collect(Collectors.toList());
});