public static < X > Iterator < X > before ( final Iterator < X > iterator , final Runnable f ) { return new Iterator < X > ( ) { private final Runnable fOnlyOnce = new RunOnlyOnce ( f ) ; @ Override public boolean hasNext ( ) { fOnlyOnce . run ( ) ; return iterator . hasNext ( ) ; } @ Override public X next ( ) { fOnlyOnce . run ( ) ; return iterator . next ( ) ; } @ Override public void remove ( ) { fOnlyOnce . run ( ) ; iterator . remove ( ) ; } } ; }
Run f immediately before the first element of iterator is generated . Exceptions raised by f will prevent the requested behavior on the underlying iterator and can be handled by the caller .