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

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

    If you don't want to create a field because you only need it locally, you can store it in an anonymous class:

    int runCount = new Object() {
        int runCount = 0;
        {
            myStream.stream()
                    .filter(...)
                    .peek(x -> runCount++)
                    .forEach(...);
        }
    }.runCount;
    

    Weird, I know. But it does keep the temporary variable out of even local scope.

提交回复
热议问题