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