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