Modifying variables inside java lambdas.
Integer list[] = {1,2,3,4,5,6,7,8};
int index = 0;
Arrays.asList(list).forEach(e -> {
System.out.println(e+" at index "+index);
index++;
});
Error :
maze2.java:22: error: local variables referenced from a lambda expression must be final or effectively final
System.out.println(e+" at index "+index);
^
maze2.java:23: error: local variables referenced from a lambda expression must be final or effectively final
index++;
^
Solution :
Integer list[] = {1,2,3,4,5,6,7,8};
int[] index = {0};
Arrays.asList(list).forEach(e -> {
System.out.println(e+" at index "+index[0]);
index[0]++;
});
Output :
1 at index 0
2 at index 1
3 at index 2
4 at index 3
5 at index 4
6 at index 5
7 at index 6
8 at index 7