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

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

    You shouldn't use AtomicInteger, you shouldn't use things unless you have a really good reason to use. And the reason for using AtomicInteger might be only allowing concurrent accesses or such as.

    When it comes to your problem;

    Holder can be use for holding and incrementing it inside a lambda. And after you can get it by calling runCount.value

    Holder runCount = new Holder<>(0);
    
    myStream.stream()
        .filter(...)
        .forEach(item -> { 
            foo();
            bar();
            runCount.value++; // now it's work fine!
        });
    System.out.println("The lambda ran " + runCount + " times");
    

提交回复
热议问题