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

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

    Another alternative is to use apache commons MutableInt.

    MutableInt cnt = new MutableInt(0);
    myStream.stream()
        .filter(...)
        .forEach(item -> { 
            foo();
            bar();
            cnt.increment();
        });
    System.out.println("The lambda ran " + cnt.getValue() + " times");
    

提交回复
热议问题