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

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

    AtomicInteger runCount = new AtomicInteger(0);
    
    elements.stream()
      //...
      .peek(runCount.incrementAndGet())
      .collect(Collectors.toList());
    
    // runCount.get() should have the num of times lambda code was executed
    

提交回复
热议问题