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

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

    An enum can be used, too. Especially if you have more than one counter in an iteration:

    import java.util.Arrays;
    
    class LambdaCounter {
    
        enum CountOf {
    
            NO,
            OK,
            ERROR;
    
            private int count;
    
            // can be named inc(), instead of the Greek capital Delta,
            // which stands for the math increment operator '∆' 
            synchronized int Δ( final int... times ) {
    
                if ( times.length <= 0 )
                    return ++count; // increase by 1
    
                return count += Arrays.stream( times ).sum(); // increase by arguments
            }
    
            // can be named val[ue](), instead of the Greek capital Xi,
            // which stands for the math identity operator '≡' 
            int Ξ() {
                return count;
            }
        }
    
        public static void main( final String[] args ) {
    
            Arrays.stream( new int[] { 1, 2, 3, 4, 5, 6, 7 } )
                .forEach( i -> {
                    CountOf.NO.Δ();
                    @SuppressWarnings( "unused" )
                    final int LHS_DUMMY =
                        i % 2 == 0
                            ? CountOf.OK.Δ()
                            : CountOf.ERROR.Δ();
                } );
            System.out.printf( "No: %d, OK: %d, Error: %d, Error.inc(38): %d, Error.inc(4, 4): %d%n",
                CountOf.NO.Ξ(), CountOf.OK.Ξ(), CountOf.ERROR.Ξ(), CountOf.ERROR.Δ( 38 ), CountOf.ERROR.Δ( 4, 4 ) );
    
            // Output:
            // No: 7, OK: 3, Error: 4, Error.inc(38): 42, Error.inc(4, 4): 50
        }
    }
    

提交回复
热议问题