I face the same problem often. I need to count the runs of a lambda for use outside the lambda.
E.g.:
myStream.stream().filter(...).forEach(item -> { ... ; runCount++});
System.out.println("The lambda ran " + runCount + "times");
The issue is that runCount needs to be final
, so it cannot be an int
. It cannot be an Integer
because that's immutable. I could make it class level variable (i.e. a field) but I'll only need it in this block of code.
I know there are various ways, I'm just curious what is your preferred solution for this?
Do you use an AtomicInteger
or an array reference or some other way?