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