public static < T > Iterator < T > cycle ( Iterator < T > itr , int times ) { // if we repeat 0, then it is as if the itr were empty, so don't take the items final List < T > items = ( times != 0 ) ? Lists . newLinkedList ( iterable ( itr ) ) : Collections . emptyList ( ) ; return new Iterator < T > ( ) { private Iterator < T > currentItr = Collections . emptyIterator ( ) ; private int ncalls = 0 ; private Iterator < T > getItr ( ) { // if this is the first call or we've gotten to the end of a round if ( ! currentItr . hasNext ( ) && ncalls < times ) { currentItr = items . iterator ( ) ; ncalls ++ ; } return currentItr ; } @ Override public boolean hasNext ( ) { return getItr ( ) . hasNext ( ) ; } @ Override public T next ( ) { return getItr ( ) . next ( ) ; } } ; }
Returns an iterator cycles over the elements in items repeat times ; if repeat < 0 then this cycles indefinitely if repeat == 0 then the iterator is an empty iterator