It works with params if you capture an array with one element, that holds the current index.
int[] idx = { 0 };
params.forEach(e -> query.bind(idx[0]++, e));
The above code assumes, that the method forEach iterates through the elements in encounter order. The interface Iterable specifies this behaviour for all classes unless otherwise documented. Apparently it works for all implementations of Iterable from the standard library, and changing this behaviour in the future would break backward-compatibility.
If you are working with Streams instead of Collections/Iterables, you should use forEachOrdered, because forEach can be executed concurrently and the elements can occur in different order. The following code works for both sequential and parallel streams:
int[] idx = { 0 };
params.stream().forEachOrdered(e -> query.bind(idx[0]++, e));
query.bind(idx++, e);
but that's all I can think ofidx
within that lambda.idx
is an instance variable or something. It will not if the code you posted is in a method/constructor body.forEach
method (basically to replace the traditional for loop in which index is manipulated manually). I think that we should not prevent more answers to be added here. Actually I would like to contribute with an answer which is suitable to this question, but not to the linked question.