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