Modifying a local variable in forEach
gives a compile error:
Normal
int ordinal = 0;
for (Example s : list) {
To have a more general solution, you can write a generic Wrapper class:
public static class Wrapper {
public T obj;
public Wrapper(T obj) { this.obj = obj; }
}
...
Wrapper w = new Wrapper<>(0);
this.forEach(s -> {
s.setOrdinal(w.obj);
w.obj++;
});
(this is a variant of the solution given by Almir Campos).
In the specific case this is not a good solution, as Integer
is worse than int
for your purpose, anyway this solution is more general I think.