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