How to get the current index in a forEach loop?

Hello,

Is it possible to have the current index of the item currently handled inside a forEach loop?

Thank you.

Method forEach() passes 3 args to its callback function: value, index and array:

1 Like

or just manually

int i=0; 

for( String s1 : list ) {

...
i++; 

}

println(i);
data.forEach(function((value, index, array){ 
    // implementation for each element in the array
});

If you don’t need to alter the array then use

data.forEach(function((value, index){ 
    // implementation for each element in the array
});

Using the fat-arrow lambda syntax:
array.forEach( (val, idx, arr) => console.log(val, idx, arr == array) );

1 Like