@ Override public Iterator < T > sample ( final Iterator < T > input ) { if ( fraction == 0 ) { return emptyIterable ; } return new SampledIterator < T > ( ) { T current = null ; @ Override public boolean hasNext ( ) { if ( current == null ) { current = getNextSampledElement ( ) ; } return current != null ; } @ Override public T next ( ) { if ( current == null ) { return getNextSampledElement ( ) ; } else { T result = current ; current = null ; return result ; } } private T getNextSampledElement ( ) { if ( fraction <= THRESHOLD ) { double rand = random . nextDouble ( ) ; double u = Math . max ( rand , EPSILON ) ; int gap = ( int ) ( Math . log ( u ) / Math . log ( 1 - fraction ) ) ; int elementCount = 0 ; if ( input . hasNext ( ) ) { T element = input . next ( ) ; while ( input . hasNext ( ) && elementCount < gap ) { element = input . next ( ) ; elementCount ++ ; } if ( elementCount < gap ) { return null ; } else { return element ; } } else { return null ; } } else { while ( input . hasNext ( ) ) { T element = input . next ( ) ; if ( random . nextDouble ( ) <= fraction ) { return element ; } } return null ; } } } ; }
Sample the input elements for each input element take a Bernoulli trail for sampling .