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