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