Nikolas Charalambidis Nikolas Charalambidis - 1 month ago 32
Java Question

How to increment a value in Java Stream?

I want to increment value of

index
with the each iteration by
1
. Easily to be achieved in the
for-loop
. The variable
image
is an array of
ImageView
.

Here is my
for-loop
.

for (Map.Entry<String, Item> entry : map.entrySet()) {
image[index].setImage(entry.getValue().getImage());
index++;
}


In order to practise Stream, I have tried to rewrite it to the
Stream
:

map.entrySet().stream()
.forEach(e -> item[index++].setImage(e.getValue().getImage()));


Causing me the error:


error: local variables referenced from a lambda expression must be final or effectively final


How to rewrite the
Stream
incrementing the variable
index
to be used in?

Answer

As Marco Topolnik suggested me in the comments above, the following code works, because it satisfies the requirement to only refer to an effectively final variable:

int[] index = {0};
map.entrySet().stream().forEach(e -> item[index[0]++].setImage(e.getValue().getImage()));