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