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