Java lambda - for loop counter is not effectively final

后端 未结 4 1896
感情败类
感情败类 2021-01-19 00:18

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

4条回答
  •  暖寄归人
    2021-01-19 00:45

    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());
    });
    

提交回复
热议问题