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