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

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

    As an alternative to sync hassling AtomicInteger one could use an integer array instead. As long as the reference to the array does not get another array assigned (and that's the point) it can be used as a final variable while the values of the fields can change arbitrarily.

        int[] iarr = {0}; // final not neccessary here if no other array is assigned
        stringList.forEach(item -> {
                iarr[0]++;
                // iarr = {1}; Error if iarr gets other array assigned
        });
    

提交回复
热议问题