public static < T > Pair < T , IterableIterator < T > > takeOneFromTopN ( Iterator < T > iterator , int n ) { if ( ! iterator . hasNext ( ) || n < 1 ) { return new Pair < T , IterableIterator < T > > ( null , iterable ( iterator ) ) ; } List < T > firstN = new ArrayList <> ( n ) ; int i = 0 ; while ( i < n && iterator . hasNext ( ) ) { firstN . add ( iterator . next ( ) ) ; i ++ ; } return new Pair <> ( firstN . remove ( ThreadLocalRandom . current ( ) . nextInt ( 0 , firstN . size ( ) ) ) , iterable ( com . google . common . collect . Iterators . concat ( com . google . common . collect . Iterators . unmodifiableIterator ( firstN . iterator ( ) ) , iterator ) ) ) ; }
Takes one of the first n items of the iterator returning that item an a new Iterator which excludes that item . Remove operation is not supported on the first n items of the returned iterator . For the remaining items remove delegates to the original Iterator .