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