Java 8: preferred way to count iterations of a lambda?

后端 未结 11 1728
没有蜡笔的小新
没有蜡笔的小新 2021-02-01 00:17

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(...).forEa         


        
11条回答
  •  生来不讨喜
    2021-02-01 00:38

    For me, this did the trick, hopefully someone finds it useful:

    AtomicInteger runCount = new AtomicInteger(0);
    myStream.stream().filter(...).forEach(item -> runCount.getAndIncrement());
    System.out.println("The lambda ran " + runCount.get() + "times");
    

    getAndIncrement() Java documentation states :

    Atomically increments the current value, with memory effects as specified by VarHandle.getAndAdd. Equivalent to getAndAdd(1).

提交回复
热议问题