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

后端 未结 11 1755
没有蜡笔的小新
没有蜡笔的小新 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:39

    AtomicInteger runCount = 0L;
    long runCount = myStream.stream()
        .filter(...)
        .peek(item -> { 
            foo();
            bar();
            runCount.incrementAndGet();
        });
    System.out.println("The lambda ran " + runCount.incrementAndGet() + "times");
    

提交回复
热议问题