001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkArgument;
020import static com.google.common.base.Preconditions.checkNotNull;
021import static com.google.common.base.Preconditions.checkState;
022import static com.google.common.base.Predicates.instanceOf;
023import static com.google.common.collect.CollectPreconditions.checkRemove;
024
025import com.google.common.annotations.Beta;
026import com.google.common.annotations.GwtCompatible;
027import com.google.common.annotations.GwtIncompatible;
028import com.google.common.base.Function;
029import com.google.common.base.Objects;
030import com.google.common.base.Optional;
031import com.google.common.base.Preconditions;
032import com.google.common.base.Predicate;
033import com.google.common.primitives.Ints;
034import com.google.errorprone.annotations.CanIgnoreReturnValue;
035import java.util.ArrayDeque;
036import java.util.Arrays;
037import java.util.Collection;
038import java.util.Collections;
039import java.util.Comparator;
040import java.util.Deque;
041import java.util.Enumeration;
042import java.util.Iterator;
043import java.util.List;
044import java.util.ListIterator;
045import java.util.NoSuchElementException;
046import java.util.PriorityQueue;
047import java.util.Queue;
048import org.checkerframework.checker.nullness.compatqual.NullableDecl;
049
050/**
051 * This class contains static utility methods that operate on or return objects of type {@link
052 * Iterator}. Except as noted, each method has a corresponding {@link Iterable}-based method in the
053 * {@link Iterables} class.
054 *
055 * <p><i>Performance notes:</i> Unless otherwise noted, all of the iterators produced in this class
056 * are <i>lazy</i>, which means that they only advance the backing iteration when absolutely
057 * necessary.
058 *
059 * <p>See the Guava User Guide section on <a href=
060 * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#iterables"> {@code
061 * Iterators}</a>.
062 *
063 * @author Kevin Bourrillion
064 * @author Jared Levy
065 * @since 2.0
066 */
067@GwtCompatible(emulated = true)
068public final class Iterators {
069  private Iterators() {}
070
071  /**
072   * Returns the empty iterator.
073   *
074   * <p>The {@link Iterable} equivalent of this method is {@link ImmutableSet#of()}.
075   */
076  static <T> UnmodifiableIterator<T> emptyIterator() {
077    return emptyListIterator();
078  }
079
080  /**
081   * Returns the empty iterator.
082   *
083   * <p>The {@link Iterable} equivalent of this method is {@link ImmutableSet#of()}.
084   */
085  // Casting to any type is safe since there are no actual elements.
086  @SuppressWarnings("unchecked")
087  static <T> UnmodifiableListIterator<T> emptyListIterator() {
088    return (UnmodifiableListIterator<T>) ArrayItr.EMPTY;
089  }
090
091  /**
092   * This is an enum singleton rather than an anonymous class so ProGuard can figure out it's only
093   * referenced by emptyModifiableIterator().
094   */
095  private enum EmptyModifiableIterator implements Iterator<Object> {
096    INSTANCE;
097
098    @Override
099    public boolean hasNext() {
100      return false;
101    }
102
103    @Override
104    public Object next() {
105      throw new NoSuchElementException();
106    }
107
108    @Override
109    public void remove() {
110      checkRemove(false);
111    }
112  }
113
114  /**
115   * Returns the empty {@code Iterator} that throws {@link IllegalStateException} instead of {@link
116   * UnsupportedOperationException} on a call to {@link Iterator#remove()}.
117   */
118  // Casting to any type is safe since there are no actual elements.
119  @SuppressWarnings("unchecked")
120  static <T> Iterator<T> emptyModifiableIterator() {
121    return (Iterator<T>) EmptyModifiableIterator.INSTANCE;
122  }
123
124  /** Returns an unmodifiable view of {@code iterator}. */
125  public static <T> UnmodifiableIterator<T> unmodifiableIterator(
126      final Iterator<? extends T> iterator) {
127    checkNotNull(iterator);
128    if (iterator instanceof UnmodifiableIterator) {
129      @SuppressWarnings("unchecked") // Since it's unmodifiable, the covariant cast is safe
130      UnmodifiableIterator<T> result = (UnmodifiableIterator<T>) iterator;
131      return result;
132    }
133    return new UnmodifiableIterator<T>() {
134      @Override
135      public boolean hasNext() {
136        return iterator.hasNext();
137      }
138
139      @Override
140      public T next() {
141        return iterator.next();
142      }
143    };
144  }
145
146  /**
147   * Simply returns its argument.
148   *
149   * @deprecated no need to use this
150   * @since 10.0
151   */
152  @Deprecated
153  public static <T> UnmodifiableIterator<T> unmodifiableIterator(UnmodifiableIterator<T> iterator) {
154    return checkNotNull(iterator);
155  }
156
157  /**
158   * Returns the number of elements remaining in {@code iterator}. The iterator will be left
159   * exhausted: its {@code hasNext()} method will return {@code false}.
160   */
161  public static int size(Iterator<?> iterator) {
162    long count = 0L;
163    while (iterator.hasNext()) {
164      iterator.next();
165      count++;
166    }
167    return Ints.saturatedCast(count);
168  }
169
170  /** Returns {@code true} if {@code iterator} contains {@code element}. */
171  public static boolean contains(Iterator<?> iterator, @NullableDecl Object element) {
172    if (element == null) {
173      while (iterator.hasNext()) {
174        if (iterator.next() == null) {
175          return true;
176        }
177      }
178    } else {
179      while (iterator.hasNext()) {
180        if (element.equals(iterator.next())) {
181          return true;
182        }
183      }
184    }
185    return false;
186  }
187
188  /**
189   * Traverses an iterator and removes every element that belongs to the provided collection. The
190   * iterator will be left exhausted: its {@code hasNext()} method will return {@code false}.
191   *
192   * @param removeFrom the iterator to (potentially) remove elements from
193   * @param elementsToRemove the elements to remove
194   * @return {@code true} if any element was removed from {@code iterator}
195   */
196  @CanIgnoreReturnValue
197  public static boolean removeAll(Iterator<?> removeFrom, Collection<?> elementsToRemove) {
198    checkNotNull(elementsToRemove);
199    boolean result = false;
200    while (removeFrom.hasNext()) {
201      if (elementsToRemove.contains(removeFrom.next())) {
202        removeFrom.remove();
203        result = true;
204      }
205    }
206    return result;
207  }
208
209  /**
210   * Removes every element that satisfies the provided predicate from the iterator. The iterator
211   * will be left exhausted: its {@code hasNext()} method will return {@code false}.
212   *
213   * @param removeFrom the iterator to (potentially) remove elements from
214   * @param predicate a predicate that determines whether an element should be removed
215   * @return {@code true} if any elements were removed from the iterator
216   * @since 2.0
217   */
218  @CanIgnoreReturnValue
219  public static <T> boolean removeIf(Iterator<T> removeFrom, Predicate<? super T> predicate) {
220    checkNotNull(predicate);
221    boolean modified = false;
222    while (removeFrom.hasNext()) {
223      if (predicate.apply(removeFrom.next())) {
224        removeFrom.remove();
225        modified = true;
226      }
227    }
228    return modified;
229  }
230
231  /**
232   * Traverses an iterator and removes every element that does not belong to the provided
233   * collection. The iterator will be left exhausted: its {@code hasNext()} method will return
234   * {@code false}.
235   *
236   * @param removeFrom the iterator to (potentially) remove elements from
237   * @param elementsToRetain the elements to retain
238   * @return {@code true} if any element was removed from {@code iterator}
239   */
240  @CanIgnoreReturnValue
241  public static boolean retainAll(Iterator<?> removeFrom, Collection<?> elementsToRetain) {
242    checkNotNull(elementsToRetain);
243    boolean result = false;
244    while (removeFrom.hasNext()) {
245      if (!elementsToRetain.contains(removeFrom.next())) {
246        removeFrom.remove();
247        result = true;
248      }
249    }
250    return result;
251  }
252
253  /**
254   * Determines whether two iterators contain equal elements in the same order. More specifically,
255   * this method returns {@code true} if {@code iterator1} and {@code iterator2} contain the same
256   * number of elements and every element of {@code iterator1} is equal to the corresponding element
257   * of {@code iterator2}.
258   *
259   * <p>Note that this will modify the supplied iterators, since they will have been advanced some
260   * number of elements forward.
261   */
262  public static boolean elementsEqual(Iterator<?> iterator1, Iterator<?> iterator2) {
263    while (iterator1.hasNext()) {
264      if (!iterator2.hasNext()) {
265        return false;
266      }
267      Object o1 = iterator1.next();
268      Object o2 = iterator2.next();
269      if (!Objects.equal(o1, o2)) {
270        return false;
271      }
272    }
273    return !iterator2.hasNext();
274  }
275
276  /**
277   * Returns a string representation of {@code iterator}, with the format {@code [e1, e2, ..., en]}.
278   * The iterator will be left exhausted: its {@code hasNext()} method will return {@code false}.
279   */
280  public static String toString(Iterator<?> iterator) {
281    StringBuilder sb = new StringBuilder().append('[');
282    boolean first = true;
283    while (iterator.hasNext()) {
284      if (!first) {
285        sb.append(", ");
286      }
287      first = false;
288      sb.append(iterator.next());
289    }
290    return sb.append(']').toString();
291  }
292
293  /**
294   * Returns the single element contained in {@code iterator}.
295   *
296   * @throws NoSuchElementException if the iterator is empty
297   * @throws IllegalArgumentException if the iterator contains multiple elements. The state of the
298   *     iterator is unspecified.
299   */
300  public static <T> T getOnlyElement(Iterator<T> iterator) {
301    T first = iterator.next();
302    if (!iterator.hasNext()) {
303      return first;
304    }
305
306    StringBuilder sb = new StringBuilder().append("expected one element but was: <").append(first);
307    for (int i = 0; i < 4 && iterator.hasNext(); i++) {
308      sb.append(", ").append(iterator.next());
309    }
310    if (iterator.hasNext()) {
311      sb.append(", ...");
312    }
313    sb.append('>');
314
315    throw new IllegalArgumentException(sb.toString());
316  }
317
318  /**
319   * Returns the single element contained in {@code iterator}, or {@code defaultValue} if the
320   * iterator is empty.
321   *
322   * @throws IllegalArgumentException if the iterator contains multiple elements. The state of the
323   *     iterator is unspecified.
324   */
325  @NullableDecl
326  public static <T> T getOnlyElement(Iterator<? extends T> iterator, @NullableDecl T defaultValue) {
327    return iterator.hasNext() ? getOnlyElement(iterator) : defaultValue;
328  }
329
330  /**
331   * Copies an iterator's elements into an array. The iterator will be left exhausted: its {@code
332   * hasNext()} method will return {@code false}.
333   *
334   * @param iterator the iterator to copy
335   * @param type the type of the elements
336   * @return a newly-allocated array into which all the elements of the iterator have been copied
337   */
338  @GwtIncompatible // Array.newInstance(Class, int)
339  public static <T> T[] toArray(Iterator<? extends T> iterator, Class<T> type) {
340    List<T> list = Lists.newArrayList(iterator);
341    return Iterables.toArray(list, type);
342  }
343
344  /**
345   * Adds all elements in {@code iterator} to {@code collection}. The iterator will be left
346   * exhausted: its {@code hasNext()} method will return {@code false}.
347   *
348   * @return {@code true} if {@code collection} was modified as a result of this operation
349   */
350  @CanIgnoreReturnValue
351  public static <T> boolean addAll(Collection<T> addTo, Iterator<? extends T> iterator) {
352    checkNotNull(addTo);
353    checkNotNull(iterator);
354    boolean wasModified = false;
355    while (iterator.hasNext()) {
356      wasModified |= addTo.add(iterator.next());
357    }
358    return wasModified;
359  }
360
361  /**
362   * Returns the number of elements in the specified iterator that equal the specified object. The
363   * iterator will be left exhausted: its {@code hasNext()} method will return {@code false}.
364   *
365   * @see Collections#frequency
366   */
367  public static int frequency(Iterator<?> iterator, @NullableDecl Object element) {
368    int count = 0;
369    while (contains(iterator, element)) {
370      // Since it lives in the same class, we know contains gets to the element and then stops,
371      // though that isn't currently publicly documented.
372      count++;
373    }
374    return count;
375  }
376
377  /**
378   * Returns an iterator that cycles indefinitely over the elements of {@code iterable}.
379   *
380   * <p>The returned iterator supports {@code remove()} if the provided iterator does. After {@code
381   * remove()} is called, subsequent cycles omit the removed element, which is no longer in {@code
382   * iterable}. The iterator's {@code hasNext()} method returns {@code true} until {@code iterable}
383   * is empty.
384   *
385   * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You
386   * should use an explicit {@code break} or be certain that you will eventually remove all the
387   * elements.
388   */
389  public static <T> Iterator<T> cycle(final Iterable<T> iterable) {
390    checkNotNull(iterable);
391    return new Iterator<T>() {
392      Iterator<T> iterator = emptyModifiableIterator();
393
394      @Override
395      public boolean hasNext() {
396        /*
397         * Don't store a new Iterator until we know the user can't remove() the last returned
398         * element anymore. Otherwise, when we remove from the old iterator, we may be invalidating
399         * the new one. The result is a ConcurrentModificationException or other bad behavior.
400         *
401         * (If we decide that we really, really hate allocating two Iterators per cycle instead of
402         * one, we can optimistically store the new Iterator and then be willing to throw it out if
403         * the user calls remove().)
404         */
405        return iterator.hasNext() || iterable.iterator().hasNext();
406      }
407
408      @Override
409      public T next() {
410        if (!iterator.hasNext()) {
411          iterator = iterable.iterator();
412          if (!iterator.hasNext()) {
413            throw new NoSuchElementException();
414          }
415        }
416        return iterator.next();
417      }
418
419      @Override
420      public void remove() {
421        iterator.remove();
422      }
423    };
424  }
425
426  /**
427   * Returns an iterator that cycles indefinitely over the provided elements.
428   *
429   * <p>The returned iterator supports {@code remove()}. After {@code remove()} is called,
430   * subsequent cycles omit the removed element, but {@code elements} does not change. The
431   * iterator's {@code hasNext()} method returns {@code true} until all of the original elements
432   * have been removed.
433   *
434   * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You
435   * should use an explicit {@code break} or be certain that you will eventually remove all the
436   * elements.
437   */
438  @SafeVarargs
439  public static <T> Iterator<T> cycle(T... elements) {
440    return cycle(Lists.newArrayList(elements));
441  }
442
443  /**
444   * Returns an Iterator that walks the specified array, nulling out elements behind it. This can
445   * avoid memory leaks when an element is no longer necessary.
446   *
447   * <p>This is mainly just to avoid the intermediate ArrayDeque in ConsumingQueueIterator.
448   */
449  private static <T> Iterator<T> consumingForArray(final T... elements) {
450    return new UnmodifiableIterator<T>() {
451      int index = 0;
452
453      @Override
454      public boolean hasNext() {
455        return index < elements.length;
456      }
457
458      @Override
459      public T next() {
460        if (!hasNext()) {
461          throw new NoSuchElementException();
462        }
463        T result = elements[index];
464        elements[index] = null;
465        index++;
466        return result;
467      }
468    };
469  }
470
471  /**
472   * Combines two iterators into a single iterator. The returned iterator iterates across the
473   * elements in {@code a}, followed by the elements in {@code b}. The source iterators are not
474   * polled until necessary.
475   *
476   * <p>The returned iterator supports {@code remove()} when the corresponding input iterator
477   * supports it.
478   */
479  public static <T> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b) {
480    checkNotNull(a);
481    checkNotNull(b);
482    return concat(consumingForArray(a, b));
483  }
484
485  /**
486   * Combines three iterators into a single iterator. The returned iterator iterates across the
487   * elements in {@code a}, followed by the elements in {@code b}, followed by the elements in
488   * {@code c}. The source iterators are not polled until necessary.
489   *
490   * <p>The returned iterator supports {@code remove()} when the corresponding input iterator
491   * supports it.
492   */
493  public static <T> Iterator<T> concat(
494      Iterator<? extends T> a, Iterator<? extends T> b, Iterator<? extends T> c) {
495    checkNotNull(a);
496    checkNotNull(b);
497    checkNotNull(c);
498    return concat(consumingForArray(a, b, c));
499  }
500
501  /**
502   * Combines four iterators into a single iterator. The returned iterator iterates across the
503   * elements in {@code a}, followed by the elements in {@code b}, followed by the elements in
504   * {@code c}, followed by the elements in {@code d}. The source iterators are not polled until
505   * necessary.
506   *
507   * <p>The returned iterator supports {@code remove()} when the corresponding input iterator
508   * supports it.
509   */
510  public static <T> Iterator<T> concat(
511      Iterator<? extends T> a,
512      Iterator<? extends T> b,
513      Iterator<? extends T> c,
514      Iterator<? extends T> d) {
515    checkNotNull(a);
516    checkNotNull(b);
517    checkNotNull(c);
518    checkNotNull(d);
519    return concat(consumingForArray(a, b, c, d));
520  }
521
522  /**
523   * Combines multiple iterators into a single iterator. The returned iterator iterates across the
524   * elements of each iterator in {@code inputs}. The input iterators are not polled until
525   * necessary.
526   *
527   * <p>The returned iterator supports {@code remove()} when the corresponding input iterator
528   * supports it.
529   *
530   * @throws NullPointerException if any of the provided iterators is null
531   */
532  public static <T> Iterator<T> concat(Iterator<? extends T>... inputs) {
533    return concatNoDefensiveCopy(Arrays.copyOf(inputs, inputs.length));
534  }
535
536  /**
537   * Combines multiple iterators into a single iterator. The returned iterator iterates across the
538   * elements of each iterator in {@code inputs}. The input iterators are not polled until
539   * necessary.
540   *
541   * <p>The returned iterator supports {@code remove()} when the corresponding input iterator
542   * supports it. The methods of the returned iterator may throw {@code NullPointerException} if any
543   * of the input iterators is null.
544   */
545  public static <T> Iterator<T> concat(Iterator<? extends Iterator<? extends T>> inputs) {
546    return new ConcatenatedIterator<T>(inputs);
547  }
548
549  /** Concats a varargs array of iterators without making a defensive copy of the array. */
550  static <T> Iterator<T> concatNoDefensiveCopy(Iterator<? extends T>... inputs) {
551    for (Iterator<? extends T> input : checkNotNull(inputs)) {
552      checkNotNull(input);
553    }
554    return concat(consumingForArray(inputs));
555  }
556
557  /**
558   * Divides an iterator into unmodifiable sublists of the given size (the final list may be
559   * smaller). For example, partitioning an iterator containing {@code [a, b, c, d, e]} with a
560   * partition size of 3 yields {@code [[a, b, c], [d, e]]} -- an outer iterator containing two
561   * inner lists of three and two elements, all in the original order.
562   *
563   * <p>The returned lists implement {@link java.util.RandomAccess}.
564   *
565   * @param iterator the iterator to return a partitioned view of
566   * @param size the desired size of each partition (the last may be smaller)
567   * @return an iterator of immutable lists containing the elements of {@code iterator} divided into
568   *     partitions
569   * @throws IllegalArgumentException if {@code size} is nonpositive
570   */
571  public static <T> UnmodifiableIterator<List<T>> partition(Iterator<T> iterator, int size) {
572    return partitionImpl(iterator, size, false);
573  }
574
575  /**
576   * Divides an iterator into unmodifiable sublists of the given size, padding the final iterator
577   * with null values if necessary. For example, partitioning an iterator containing {@code [a, b,
578   * c, d, e]} with a partition size of 3 yields {@code [[a, b, c], [d, e, null]]} -- an outer
579   * iterator containing two inner lists of three elements each, all in the original order.
580   *
581   * <p>The returned lists implement {@link java.util.RandomAccess}.
582   *
583   * @param iterator the iterator to return a partitioned view of
584   * @param size the desired size of each partition
585   * @return an iterator of immutable lists containing the elements of {@code iterator} divided into
586   *     partitions (the final iterable may have trailing null elements)
587   * @throws IllegalArgumentException if {@code size} is nonpositive
588   */
589  public static <T> UnmodifiableIterator<List<T>> paddedPartition(Iterator<T> iterator, int size) {
590    return partitionImpl(iterator, size, true);
591  }
592
593  private static <T> UnmodifiableIterator<List<T>> partitionImpl(
594      final Iterator<T> iterator, final int size, final boolean pad) {
595    checkNotNull(iterator);
596    checkArgument(size > 0);
597    return new UnmodifiableIterator<List<T>>() {
598      @Override
599      public boolean hasNext() {
600        return iterator.hasNext();
601      }
602
603      @Override
604      public List<T> next() {
605        if (!hasNext()) {
606          throw new NoSuchElementException();
607        }
608        Object[] array = new Object[size];
609        int count = 0;
610        for (; count < size && iterator.hasNext(); count++) {
611          array[count] = iterator.next();
612        }
613        for (int i = count; i < size; i++) {
614          array[i] = null; // for GWT
615        }
616
617        @SuppressWarnings("unchecked") // we only put Ts in it
618        List<T> list = Collections.unmodifiableList((List<T>) Arrays.asList(array));
619        return (pad || count == size) ? list : list.subList(0, count);
620      }
621    };
622  }
623
624  /**
625   * Returns a view of {@code unfiltered} containing all elements that satisfy the input predicate
626   * {@code retainIfTrue}.
627   */
628  public static <T> UnmodifiableIterator<T> filter(
629      final Iterator<T> unfiltered, final Predicate<? super T> retainIfTrue) {
630    checkNotNull(unfiltered);
631    checkNotNull(retainIfTrue);
632    return new AbstractIterator<T>() {
633      @Override
634      protected T computeNext() {
635        while (unfiltered.hasNext()) {
636          T element = unfiltered.next();
637          if (retainIfTrue.apply(element)) {
638            return element;
639          }
640        }
641        return endOfData();
642      }
643    };
644  }
645
646  /**
647   * Returns a view of {@code unfiltered} containing all elements that are of the type {@code
648   * desiredType}.
649   */
650  @SuppressWarnings("unchecked") // can cast to <T> because non-Ts are removed
651  @GwtIncompatible // Class.isInstance
652  public static <T> UnmodifiableIterator<T> filter(Iterator<?> unfiltered, Class<T> desiredType) {
653    return (UnmodifiableIterator<T>) filter(unfiltered, instanceOf(desiredType));
654  }
655
656  /**
657   * Returns {@code true} if one or more elements returned by {@code iterator} satisfy the given
658   * predicate.
659   */
660  public static <T> boolean any(Iterator<T> iterator, Predicate<? super T> predicate) {
661    return indexOf(iterator, predicate) != -1;
662  }
663
664  /**
665   * Returns {@code true} if every element returned by {@code iterator} satisfies the given
666   * predicate. If {@code iterator} is empty, {@code true} is returned.
667   */
668  public static <T> boolean all(Iterator<T> iterator, Predicate<? super T> predicate) {
669    checkNotNull(predicate);
670    while (iterator.hasNext()) {
671      T element = iterator.next();
672      if (!predicate.apply(element)) {
673        return false;
674      }
675    }
676    return true;
677  }
678
679  /**
680   * Returns the first element in {@code iterator} that satisfies the given predicate; use this
681   * method only when such an element is known to exist. If no such element is found, the iterator
682   * will be left exhausted: its {@code hasNext()} method will return {@code false}. If it is
683   * possible that <i>no</i> element will match, use {@link #tryFind} or {@link #find(Iterator,
684   * Predicate, Object)} instead.
685   *
686   * @throws NoSuchElementException if no element in {@code iterator} matches the given predicate
687   */
688  public static <T> T find(Iterator<T> iterator, Predicate<? super T> predicate) {
689    checkNotNull(iterator);
690    checkNotNull(predicate);
691    while (iterator.hasNext()) {
692      T t = iterator.next();
693      if (predicate.apply(t)) {
694        return t;
695      }
696    }
697    throw new NoSuchElementException();
698  }
699
700  /**
701   * Returns the first element in {@code iterator} that satisfies the given predicate. If no such
702   * element is found, {@code defaultValue} will be returned from this method and the iterator will
703   * be left exhausted: its {@code hasNext()} method will return {@code false}. Note that this can
704   * usually be handled more naturally using {@code tryFind(iterator, predicate).or(defaultValue)}.
705   *
706   * @since 7.0
707   */
708  @NullableDecl
709  public static <T> T find(
710      Iterator<? extends T> iterator,
711      Predicate<? super T> predicate,
712      @NullableDecl T defaultValue) {
713    checkNotNull(iterator);
714    checkNotNull(predicate);
715    while (iterator.hasNext()) {
716      T t = iterator.next();
717      if (predicate.apply(t)) {
718        return t;
719      }
720    }
721    return defaultValue;
722  }
723
724  /**
725   * Returns an {@link Optional} containing the first element in {@code iterator} that satisfies the
726   * given predicate, if such an element exists. If no such element is found, an empty {@link
727   * Optional} will be returned from this method and the iterator will be left exhausted: its {@code
728   * hasNext()} method will return {@code false}.
729   *
730   * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code null}. If {@code null}
731   * is matched in {@code iterator}, a NullPointerException will be thrown.
732   *
733   * @since 11.0
734   */
735  public static <T> Optional<T> tryFind(Iterator<T> iterator, Predicate<? super T> predicate) {
736    checkNotNull(iterator);
737    checkNotNull(predicate);
738    while (iterator.hasNext()) {
739      T t = iterator.next();
740      if (predicate.apply(t)) {
741        return Optional.of(t);
742      }
743    }
744    return Optional.absent();
745  }
746
747  /**
748   * Returns the index in {@code iterator} of the first element that satisfies the provided {@code
749   * predicate}, or {@code -1} if the Iterator has no such elements.
750   *
751   * <p>More formally, returns the lowest index {@code i} such that {@code
752   * predicate.apply(Iterators.get(iterator, i))} returns {@code true}, or {@code -1} if there is no
753   * such index.
754   *
755   * <p>If -1 is returned, the iterator will be left exhausted: its {@code hasNext()} method will
756   * return {@code false}. Otherwise, the iterator will be set to the element which satisfies the
757   * {@code predicate}.
758   *
759   * @since 2.0
760   */
761  public static <T> int indexOf(Iterator<T> iterator, Predicate<? super T> predicate) {
762    checkNotNull(predicate, "predicate");
763    for (int i = 0; iterator.hasNext(); i++) {
764      T current = iterator.next();
765      if (predicate.apply(current)) {
766        return i;
767      }
768    }
769    return -1;
770  }
771
772  /**
773   * Returns a view containing the result of applying {@code function} to each element of {@code
774   * fromIterator}.
775   *
776   * <p>The returned iterator supports {@code remove()} if {@code fromIterator} does. After a
777   * successful {@code remove()} call, {@code fromIterator} no longer contains the corresponding
778   * element.
779   */
780  public static <F, T> Iterator<T> transform(
781      final Iterator<F> fromIterator, final Function<? super F, ? extends T> function) {
782    checkNotNull(function);
783    return new TransformedIterator<F, T>(fromIterator) {
784      @Override
785      T transform(F from) {
786        return function.apply(from);
787      }
788    };
789  }
790
791  /**
792   * Advances {@code iterator} {@code position + 1} times, returning the element at the {@code
793   * position}th position.
794   *
795   * @param position position of the element to return
796   * @return the element at the specified position in {@code iterator}
797   * @throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to
798   *     the number of elements remaining in {@code iterator}
799   */
800  public static <T> T get(Iterator<T> iterator, int position) {
801    checkNonnegative(position);
802    int skipped = advance(iterator, position);
803    if (!iterator.hasNext()) {
804      throw new IndexOutOfBoundsException(
805          "position ("
806              + position
807              + ") must be less than the number of elements that remained ("
808              + skipped
809              + ")");
810    }
811    return iterator.next();
812  }
813
814  /**
815   * Advances {@code iterator} {@code position + 1} times, returning the element at the {@code
816   * position}th position or {@code defaultValue} otherwise.
817   *
818   * @param position position of the element to return
819   * @param defaultValue the default value to return if the iterator is empty or if {@code position}
820   *     is greater than the number of elements remaining in {@code iterator}
821   * @return the element at the specified position in {@code iterator} or {@code defaultValue} if
822   *     {@code iterator} produces fewer than {@code position + 1} elements.
823   * @throws IndexOutOfBoundsException if {@code position} is negative
824   * @since 4.0
825   */
826  @NullableDecl
827  public static <T> T get(
828      Iterator<? extends T> iterator, int position, @NullableDecl T defaultValue) {
829    checkNonnegative(position);
830    advance(iterator, position);
831    return getNext(iterator, defaultValue);
832  }
833
834  static void checkNonnegative(int position) {
835    if (position < 0) {
836      throw new IndexOutOfBoundsException("position (" + position + ") must not be negative");
837    }
838  }
839
840  /**
841   * Returns the next element in {@code iterator} or {@code defaultValue} if the iterator is empty.
842   * The {@link Iterables} analog to this method is {@link Iterables#getFirst}.
843   *
844   * @param defaultValue the default value to return if the iterator is empty
845   * @return the next element of {@code iterator} or the default value
846   * @since 7.0
847   */
848  @NullableDecl
849  public static <T> T getNext(Iterator<? extends T> iterator, @NullableDecl T defaultValue) {
850    return iterator.hasNext() ? iterator.next() : defaultValue;
851  }
852
853  /**
854   * Advances {@code iterator} to the end, returning the last element.
855   *
856   * @return the last element of {@code iterator}
857   * @throws NoSuchElementException if the iterator is empty
858   */
859  public static <T> T getLast(Iterator<T> iterator) {
860    while (true) {
861      T current = iterator.next();
862      if (!iterator.hasNext()) {
863        return current;
864      }
865    }
866  }
867
868  /**
869   * Advances {@code iterator} to the end, returning the last element or {@code defaultValue} if the
870   * iterator is empty.
871   *
872   * @param defaultValue the default value to return if the iterator is empty
873   * @return the last element of {@code iterator}
874   * @since 3.0
875   */
876  @NullableDecl
877  public static <T> T getLast(Iterator<? extends T> iterator, @NullableDecl T defaultValue) {
878    return iterator.hasNext() ? getLast(iterator) : defaultValue;
879  }
880
881  /**
882   * Calls {@code next()} on {@code iterator}, either {@code numberToAdvance} times or until {@code
883   * hasNext()} returns {@code false}, whichever comes first.
884   *
885   * @return the number of elements the iterator was advanced
886   * @since 13.0 (since 3.0 as {@code Iterators.skip})
887   */
888  @CanIgnoreReturnValue
889  public static int advance(Iterator<?> iterator, int numberToAdvance) {
890    checkNotNull(iterator);
891    checkArgument(numberToAdvance >= 0, "numberToAdvance must be nonnegative");
892
893    int i;
894    for (i = 0; i < numberToAdvance && iterator.hasNext(); i++) {
895      iterator.next();
896    }
897    return i;
898  }
899
900  /**
901   * Returns a view containing the first {@code limitSize} elements of {@code iterator}. If {@code
902   * iterator} contains fewer than {@code limitSize} elements, the returned view contains all of its
903   * elements. The returned iterator supports {@code remove()} if {@code iterator} does.
904   *
905   * @param iterator the iterator to limit
906   * @param limitSize the maximum number of elements in the returned iterator
907   * @throws IllegalArgumentException if {@code limitSize} is negative
908   * @since 3.0
909   */
910  public static <T> Iterator<T> limit(final Iterator<T> iterator, final int limitSize) {
911    checkNotNull(iterator);
912    checkArgument(limitSize >= 0, "limit is negative");
913    return new Iterator<T>() {
914      private int count;
915
916      @Override
917      public boolean hasNext() {
918        return count < limitSize && iterator.hasNext();
919      }
920
921      @Override
922      public T next() {
923        if (!hasNext()) {
924          throw new NoSuchElementException();
925        }
926        count++;
927        return iterator.next();
928      }
929
930      @Override
931      public void remove() {
932        iterator.remove();
933      }
934    };
935  }
936
937  /**
938   * Returns a view of the supplied {@code iterator} that removes each element from the supplied
939   * {@code iterator} as it is returned.
940   *
941   * <p>The provided iterator must support {@link Iterator#remove()} or else the returned iterator
942   * will fail on the first call to {@code next}.
943   *
944   * @param iterator the iterator to remove and return elements from
945   * @return an iterator that removes and returns elements from the supplied iterator
946   * @since 2.0
947   */
948  public static <T> Iterator<T> consumingIterator(final Iterator<T> iterator) {
949    checkNotNull(iterator);
950    return new UnmodifiableIterator<T>() {
951      @Override
952      public boolean hasNext() {
953        return iterator.hasNext();
954      }
955
956      @Override
957      public T next() {
958        T next = iterator.next();
959        iterator.remove();
960        return next;
961      }
962
963      @Override
964      public String toString() {
965        return "Iterators.consumingIterator(...)";
966      }
967    };
968  }
969
970  /**
971   * Deletes and returns the next value from the iterator, or returns {@code null} if there is no
972   * such value.
973   */
974  @NullableDecl
975  static <T> T pollNext(Iterator<T> iterator) {
976    if (iterator.hasNext()) {
977      T result = iterator.next();
978      iterator.remove();
979      return result;
980    } else {
981      return null;
982    }
983  }
984
985  // Methods only in Iterators, not in Iterables
986
987  /** Clears the iterator using its remove method. */
988  static void clear(Iterator<?> iterator) {
989    checkNotNull(iterator);
990    while (iterator.hasNext()) {
991      iterator.next();
992      iterator.remove();
993    }
994  }
995
996  /**
997   * Returns an iterator containing the elements of {@code array} in order. The returned iterator is
998   * a view of the array; subsequent changes to the array will be reflected in the iterator.
999   *
1000   * <p><b>Note:</b> It is often preferable to represent your data using a collection type, for
1001   * example using {@link Arrays#asList(Object[])}, making this method unnecessary.
1002   *
1003   * <p>The {@code Iterable} equivalent of this method is either {@link Arrays#asList(Object[])},
1004   * {@link ImmutableList#copyOf(Object[])}}, or {@link ImmutableList#of}.
1005   */
1006  @SafeVarargs
1007  public static <T> UnmodifiableIterator<T> forArray(final T... array) {
1008    return forArray(array, 0, array.length, 0);
1009  }
1010
1011  /**
1012   * Returns a list iterator containing the elements in the specified range of {@code array} in
1013   * order, starting at the specified index.
1014   *
1015   * <p>The {@code Iterable} equivalent of this method is {@code
1016   * Arrays.asList(array).subList(offset, offset + length).listIterator(index)}.
1017   */
1018  static <T> UnmodifiableListIterator<T> forArray(
1019      final T[] array, final int offset, int length, int index) {
1020    checkArgument(length >= 0);
1021    int end = offset + length;
1022
1023    // Technically we should give a slightly more descriptive error on overflow
1024    Preconditions.checkPositionIndexes(offset, end, array.length);
1025    Preconditions.checkPositionIndex(index, length);
1026    if (length == 0) {
1027      return emptyListIterator();
1028    }
1029    return new ArrayItr<T>(array, offset, length, index);
1030  }
1031
1032  private static final class ArrayItr<T> extends AbstractIndexedListIterator<T> {
1033    static final UnmodifiableListIterator<Object> EMPTY = new ArrayItr<>(new Object[0], 0, 0, 0);
1034
1035    private final T[] array;
1036    private final int offset;
1037
1038    ArrayItr(T[] array, int offset, int length, int index) {
1039      super(length, index);
1040      this.array = array;
1041      this.offset = offset;
1042    }
1043
1044    @Override
1045    protected T get(int index) {
1046      return array[offset + index];
1047    }
1048  }
1049
1050  /**
1051   * Returns an iterator containing only {@code value}.
1052   *
1053   * <p>The {@link Iterable} equivalent of this method is {@link Collections#singleton}.
1054   */
1055  public static <T> UnmodifiableIterator<T> singletonIterator(@NullableDecl final T value) {
1056    return new UnmodifiableIterator<T>() {
1057      boolean done;
1058
1059      @Override
1060      public boolean hasNext() {
1061        return !done;
1062      }
1063
1064      @Override
1065      public T next() {
1066        if (done) {
1067          throw new NoSuchElementException();
1068        }
1069        done = true;
1070        return value;
1071      }
1072    };
1073  }
1074
1075  /**
1076   * Adapts an {@code Enumeration} to the {@code Iterator} interface.
1077   *
1078   * <p>This method has no equivalent in {@link Iterables} because viewing an {@code Enumeration} as
1079   * an {@code Iterable} is impossible. However, the contents can be <i>copied</i> into a collection
1080   * using {@link Collections#list}.
1081   */
1082  public static <T> UnmodifiableIterator<T> forEnumeration(final Enumeration<T> enumeration) {
1083    checkNotNull(enumeration);
1084    return new UnmodifiableIterator<T>() {
1085      @Override
1086      public boolean hasNext() {
1087        return enumeration.hasMoreElements();
1088      }
1089
1090      @Override
1091      public T next() {
1092        return enumeration.nextElement();
1093      }
1094    };
1095  }
1096
1097  /**
1098   * Adapts an {@code Iterator} to the {@code Enumeration} interface.
1099   *
1100   * <p>The {@code Iterable} equivalent of this method is either {@link Collections#enumeration} (if
1101   * you have a {@link Collection}), or {@code Iterators.asEnumeration(collection.iterator())}.
1102   */
1103  public static <T> Enumeration<T> asEnumeration(final Iterator<T> iterator) {
1104    checkNotNull(iterator);
1105    return new Enumeration<T>() {
1106      @Override
1107      public boolean hasMoreElements() {
1108        return iterator.hasNext();
1109      }
1110
1111      @Override
1112      public T nextElement() {
1113        return iterator.next();
1114      }
1115    };
1116  }
1117
1118  /** Implementation of PeekingIterator that avoids peeking unless necessary. */
1119  private static class PeekingImpl<E> implements PeekingIterator<E> {
1120
1121    private final Iterator<? extends E> iterator;
1122    private boolean hasPeeked;
1123    @NullableDecl private E peekedElement;
1124
1125    public PeekingImpl(Iterator<? extends E> iterator) {
1126      this.iterator = checkNotNull(iterator);
1127    }
1128
1129    @Override
1130    public boolean hasNext() {
1131      return hasPeeked || iterator.hasNext();
1132    }
1133
1134    @Override
1135    public E next() {
1136      if (!hasPeeked) {
1137        return iterator.next();
1138      }
1139      E result = peekedElement;
1140      hasPeeked = false;
1141      peekedElement = null;
1142      return result;
1143    }
1144
1145    @Override
1146    public void remove() {
1147      checkState(!hasPeeked, "Can't remove after you've peeked at next");
1148      iterator.remove();
1149    }
1150
1151    @Override
1152    public E peek() {
1153      if (!hasPeeked) {
1154        peekedElement = iterator.next();
1155        hasPeeked = true;
1156      }
1157      return peekedElement;
1158    }
1159  }
1160
1161  /**
1162   * Returns a {@code PeekingIterator} backed by the given iterator.
1163   *
1164   * <p>Calls to the {@code peek} method with no intervening calls to {@code next} do not affect the
1165   * iteration, and hence return the same object each time. A subsequent call to {@code next} is
1166   * guaranteed to return the same object again. For example:
1167   *
1168   * <pre>{@code
1169   * PeekingIterator<String> peekingIterator =
1170   *     Iterators.peekingIterator(Iterators.forArray("a", "b"));
1171   * String a1 = peekingIterator.peek(); // returns "a"
1172   * String a2 = peekingIterator.peek(); // also returns "a"
1173   * String a3 = peekingIterator.next(); // also returns "a"
1174   * }</pre>
1175   *
1176   * <p>Any structural changes to the underlying iteration (aside from those performed by the
1177   * iterator's own {@link PeekingIterator#remove()} method) will leave the iterator in an undefined
1178   * state.
1179   *
1180   * <p>The returned iterator does not support removal after peeking, as explained by {@link
1181   * PeekingIterator#remove()}.
1182   *
1183   * <p>Note: If the given iterator is already a {@code PeekingIterator}, it <i>might</i> be
1184   * returned to the caller, although this is neither guaranteed to occur nor required to be
1185   * consistent. For example, this method <i>might</i> choose to pass through recognized
1186   * implementations of {@code PeekingIterator} when the behavior of the implementation is known to
1187   * meet the contract guaranteed by this method.
1188   *
1189   * <p>There is no {@link Iterable} equivalent to this method, so use this method to wrap each
1190   * individual iterator as it is generated.
1191   *
1192   * @param iterator the backing iterator. The {@link PeekingIterator} assumes ownership of this
1193   *     iterator, so users should cease making direct calls to it after calling this method.
1194   * @return a peeking iterator backed by that iterator. Apart from the additional {@link
1195   *     PeekingIterator#peek()} method, this iterator behaves exactly the same as {@code iterator}.
1196   */
1197  public static <T> PeekingIterator<T> peekingIterator(Iterator<? extends T> iterator) {
1198    if (iterator instanceof PeekingImpl) {
1199      // Safe to cast <? extends T> to <T> because PeekingImpl only uses T
1200      // covariantly (and cannot be subclassed to add non-covariant uses).
1201      @SuppressWarnings("unchecked")
1202      PeekingImpl<T> peeking = (PeekingImpl<T>) iterator;
1203      return peeking;
1204    }
1205    return new PeekingImpl<T>(iterator);
1206  }
1207
1208  /**
1209   * Simply returns its argument.
1210   *
1211   * @deprecated no need to use this
1212   * @since 10.0
1213   */
1214  @Deprecated
1215  public static <T> PeekingIterator<T> peekingIterator(PeekingIterator<T> iterator) {
1216    return checkNotNull(iterator);
1217  }
1218
1219  /**
1220   * Returns an iterator over the merged contents of all given {@code iterators}, traversing every
1221   * element of the input iterators. Equivalent entries will not be de-duplicated.
1222   *
1223   * <p>Callers must ensure that the source {@code iterators} are in non-descending order as this
1224   * method does not sort its input.
1225   *
1226   * <p>For any equivalent elements across all {@code iterators}, it is undefined which element is
1227   * returned first.
1228   *
1229   * @since 11.0
1230   */
1231  @Beta
1232  public static <T> UnmodifiableIterator<T> mergeSorted(
1233      Iterable<? extends Iterator<? extends T>> iterators, Comparator<? super T> comparator) {
1234    checkNotNull(iterators, "iterators");
1235    checkNotNull(comparator, "comparator");
1236
1237    return new MergingIterator<T>(iterators, comparator);
1238  }
1239
1240  /**
1241   * An iterator that performs a lazy N-way merge, calculating the next value each time the iterator
1242   * is polled. This amortizes the sorting cost over the iteration and requires less memory than
1243   * sorting all elements at once.
1244   *
1245   * <p>Retrieving a single element takes approximately O(log(M)) time, where M is the number of
1246   * iterators. (Retrieving all elements takes approximately O(N*log(M)) time, where N is the total
1247   * number of elements.)
1248   */
1249  private static class MergingIterator<T> extends UnmodifiableIterator<T> {
1250    final Queue<PeekingIterator<T>> queue;
1251
1252    public MergingIterator(
1253        Iterable<? extends Iterator<? extends T>> iterators,
1254        final Comparator<? super T> itemComparator) {
1255      // A comparator that's used by the heap, allowing the heap
1256      // to be sorted based on the top of each iterator.
1257      Comparator<PeekingIterator<T>> heapComparator =
1258          new Comparator<PeekingIterator<T>>() {
1259            @Override
1260            public int compare(PeekingIterator<T> o1, PeekingIterator<T> o2) {
1261              return itemComparator.compare(o1.peek(), o2.peek());
1262            }
1263          };
1264
1265      queue = new PriorityQueue<>(2, heapComparator);
1266
1267      for (Iterator<? extends T> iterator : iterators) {
1268        if (iterator.hasNext()) {
1269          queue.add(Iterators.peekingIterator(iterator));
1270        }
1271      }
1272    }
1273
1274    @Override
1275    public boolean hasNext() {
1276      return !queue.isEmpty();
1277    }
1278
1279    @Override
1280    public T next() {
1281      PeekingIterator<T> nextIter = queue.remove();
1282      T next = nextIter.next();
1283      if (nextIter.hasNext()) {
1284        queue.add(nextIter);
1285      }
1286      return next;
1287    }
1288  }
1289
1290  private static class ConcatenatedIterator<T> implements Iterator<T> {
1291    /* The last iterator to return an element.  Calls to remove() go to this iterator. */
1292    @NullableDecl private Iterator<? extends T> toRemove;
1293
1294    /* The iterator currently returning elements. */
1295    private Iterator<? extends T> iterator;
1296
1297    /*
1298     * We track the "meta iterators," the iterators-of-iterators, below.  Usually, topMetaIterator
1299     * is the only one in use, but if we encounter nested concatenations, we start a deque of
1300     * meta-iterators rather than letting the nesting get arbitrarily deep.  This keeps each
1301     * operation O(1).
1302     */
1303
1304    private Iterator<? extends Iterator<? extends T>> topMetaIterator;
1305
1306    // Only becomes nonnull if we encounter nested concatenations.
1307    @NullableDecl private Deque<Iterator<? extends Iterator<? extends T>>> metaIterators;
1308
1309    ConcatenatedIterator(Iterator<? extends Iterator<? extends T>> metaIterator) {
1310      iterator = emptyIterator();
1311      topMetaIterator = checkNotNull(metaIterator);
1312    }
1313
1314    // Returns a nonempty meta-iterator or, if all meta-iterators are empty, null.
1315    @NullableDecl
1316    private Iterator<? extends Iterator<? extends T>> getTopMetaIterator() {
1317      while (topMetaIterator == null || !topMetaIterator.hasNext()) {
1318        if (metaIterators != null && !metaIterators.isEmpty()) {
1319          topMetaIterator = metaIterators.removeFirst();
1320        } else {
1321          return null;
1322        }
1323      }
1324      return topMetaIterator;
1325    }
1326
1327    @Override
1328    public boolean hasNext() {
1329      while (!checkNotNull(iterator).hasNext()) {
1330        // this weird checkNotNull positioning appears required by our tests, which expect
1331        // both hasNext and next to throw NPE if an input iterator is null.
1332
1333        topMetaIterator = getTopMetaIterator();
1334        if (topMetaIterator == null) {
1335          return false;
1336        }
1337
1338        iterator = topMetaIterator.next();
1339
1340        if (iterator instanceof ConcatenatedIterator) {
1341          // Instead of taking linear time in the number of nested concatenations, unpack
1342          // them into the queue
1343          @SuppressWarnings("unchecked")
1344          ConcatenatedIterator<T> topConcat = (ConcatenatedIterator<T>) iterator;
1345          iterator = topConcat.iterator;
1346
1347          // topConcat.topMetaIterator, then topConcat.metaIterators, then this.topMetaIterator,
1348          // then this.metaIterators
1349
1350          if (this.metaIterators == null) {
1351            this.metaIterators = new ArrayDeque<>();
1352          }
1353          this.metaIterators.addFirst(this.topMetaIterator);
1354          if (topConcat.metaIterators != null) {
1355            while (!topConcat.metaIterators.isEmpty()) {
1356              this.metaIterators.addFirst(topConcat.metaIterators.removeLast());
1357            }
1358          }
1359          this.topMetaIterator = topConcat.topMetaIterator;
1360        }
1361      }
1362      return true;
1363    }
1364
1365    @Override
1366    public T next() {
1367      if (hasNext()) {
1368        toRemove = iterator;
1369        return iterator.next();
1370      } else {
1371        throw new NoSuchElementException();
1372      }
1373    }
1374
1375    @Override
1376    public void remove() {
1377      CollectPreconditions.checkRemove(toRemove != null);
1378      toRemove.remove();
1379      toRemove = null;
1380    }
1381  }
1382
1383  /** Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 */
1384  static <T> ListIterator<T> cast(Iterator<T> iterator) {
1385    return (ListIterator<T>) iterator;
1386  }
1387}