Class Iterators
Iterator. Except as noted, each method has a corresponding Iterable-based method in the
Iterables class.
Performance notes: Unless otherwise noted, all of the iterators produced in this class are lazy, which means that they only advance the backing iteration when absolutely necessary.
See the Guava User Guide section on
Iterators.
- Since:
- 2.0
- Author:
- Kevin Bourrillion, Jared Levy
-
Method Summary
Modifier and TypeMethodDescriptionaddAll(Collection<T> addTo, Iterator<? extends T> iterator) Adds all elements initeratortocollection.static intCallsnext()oniterator, eithernumberToAdvancetimes or untilhasNext()returnsfalse, whichever comes first.Returnstrueif every element returned byiteratorsatisfies the given predicate.Returnstrueif one or more elements returned byiteratorsatisfy the given predicate.static <T extends @Nullable Object>
Enumeration<T> asEnumeration(Iterator<T> iterator) Adapts anIteratorto theEnumerationinterface.Combines multiple iterators into a single iterator.Combines multiple iterators into a single iterator.Combines two iterators into a single iterator.Combines three iterators into a single iterator.concat(Iterator<? extends T> a, Iterator<? extends T> b, Iterator<? extends T> c, Iterator<? extends T> d) Combines four iterators into a single iterator.consumingIterator(Iterator<T> iterator) Returns a view of the suppliediteratorthat removes each element from the suppliediteratoras it is returned.static booleanReturnstrueifiteratorcontainselement.Returns an iterator that cycles indefinitely over the elements ofiterable.cycle(T... elements) Returns an iterator that cycles indefinitely over the provided elements.static booleanelementsEqual(Iterator<?> iterator1, Iterator<?> iterator2) Determines whether two iterators contain equal elements in the same order.static <T> UnmodifiableIterator<T> Returns a view ofunfilteredcontaining all elements that are of the typedesiredType.static <T extends @Nullable Object>
UnmodifiableIterator<T> Returns a view ofunfilteredcontaining all elements that satisfy the input predicateretainIfTrue.Returns the first element initeratorthat satisfies the given predicate.Returns the first element initeratorthat satisfies the given predicate; use this method only when such an element is known to exist.static <T extends @Nullable Object>
UnmodifiableIterator<T> forArray(T... array) Returns an iterator containing the elements ofarrayin order.static <T extends @Nullable Object>
UnmodifiableIterator<T> forEnumeration(Enumeration<T> enumeration) Adapts anEnumerationto theIteratorinterface.static intReturns the number of elements in the specified iterator that equal the specified object.Advancesiteratorposition + 1times, returning the element at thepositionth position ordefaultValueotherwise.Advancesiteratorposition + 1times, returning the element at thepositionth position.Advancesiteratorto the end, returning the last element ordefaultValueif the iterator is empty.Advancesiteratorto the end, returning the last element.Returns the next element initeratorordefaultValueif the iterator is empty.getOnlyElement(Iterator<? extends T> iterator, T defaultValue) Returns the single element contained initerator, ordefaultValueif the iterator is empty.getOnlyElement(Iterator<T> iterator) Returns the single element contained initerator.Returns the index initeratorof the first element that satisfies the providedpredicate, or-1if the Iterator has no such elements.Returns a view containing the firstlimitSizeelements ofiterator.static <T extends @Nullable Object>
UnmodifiableIterator<T> mergeSorted(Iterable<? extends Iterator<? extends T>> iterators, Comparator<? super T> comparator) Returns an iterator over the merged contents of all giveniterators, traversing every element of the input iterators.static <T extends @Nullable Object>
UnmodifiableIterator<List<@Nullable T>> paddedPartition(Iterator<T> iterator, int size) Divides an iterator into unmodifiable sublists of the given size, padding the final iterator with null values if necessary.static <T extends @Nullable Object>
UnmodifiableIterator<List<T>> Divides an iterator into unmodifiable sublists of the given size (the final list may be smaller).static <T extends @Nullable Object>
PeekingIterator<T> peekingIterator(PeekingIterator<T> iterator) Deprecated.no need to use thisstatic <T extends @Nullable Object>
PeekingIterator<T> peekingIterator(Iterator<? extends T> iterator) Returns aPeekingIteratorbacked by the given iterator.static booleanremoveAll(Iterator<?> removeFrom, Collection<?> elementsToRemove) Traverses an iterator and removes every element that belongs to the provided collection.Removes every element that satisfies the provided predicate from the iterator.static booleanretainAll(Iterator<?> removeFrom, Collection<?> elementsToRetain) Traverses an iterator and removes every element that does not belong to the provided collection.static <T extends @Nullable Object>
UnmodifiableIterator<T> singletonIterator(T value) Returns an iterator containing onlyvalue.static intReturns the number of elements remaining initerator.Copies an iterator's elements into an array.static StringReturns a string representation ofiterator, with the format[e1, e2, ..., en].Returns a view containing the result of applyingfunctionto each element offromIterator.static <T> Optional<T> Returns anOptionalcontaining the first element initeratorthat satisfies the given predicate, if such an element exists.static <T extends @Nullable Object>
UnmodifiableIterator<T> unmodifiableIterator(UnmodifiableIterator<T> iterator) Deprecated.no need to use thisstatic <T extends @Nullable Object>
UnmodifiableIterator<T> unmodifiableIterator(Iterator<? extends T> iterator) Returns an unmodifiable view ofiterator.
-
Method Details
-
unmodifiableIterator
public static <T extends @Nullable Object> UnmodifiableIterator<T> unmodifiableIterator(Iterator<? extends T> iterator) Returns an unmodifiable view ofiterator. -
unmodifiableIterator
@InlineMe(replacement="checkNotNull(iterator)", staticImports="com.google.common.base.Preconditions.checkNotNull") @Deprecated public static <T extends @Nullable Object> UnmodifiableIterator<T> unmodifiableIterator(UnmodifiableIterator<T> iterator) Deprecated.no need to use thisSimply returns its argument.- Since:
- 10.0
-
size
Returns the number of elements remaining initerator. The iterator will be left exhausted: itshasNext()method will returnfalse. -
contains
-
removeAll
@CanIgnoreReturnValue public static boolean removeAll(Iterator<?> removeFrom, Collection<?> elementsToRemove) Traverses an iterator and removes every element that belongs to the provided collection. The iterator will be left exhausted: itshasNext()method will returnfalse.- Parameters:
removeFrom- the iterator to (potentially) remove elements fromelementsToRemove- the elements to remove- Returns:
trueif any element was removed fromiterator
-
removeIf
@CanIgnoreReturnValue public static <T extends @Nullable Object> boolean removeIf(Iterator<T> removeFrom, Predicate<? super T> predicate) Removes every element that satisfies the provided predicate from the iterator. The iterator will be left exhausted: itshasNext()method will returnfalse.- Parameters:
removeFrom- the iterator to (potentially) remove elements frompredicate- a predicate that determines whether an element should be removed- Returns:
trueif any elements were removed from the iterator- Since:
- 2.0
-
retainAll
@CanIgnoreReturnValue public static boolean retainAll(Iterator<?> removeFrom, Collection<?> elementsToRetain) Traverses an iterator and removes every element that does not belong to the provided collection. The iterator will be left exhausted: itshasNext()method will returnfalse.- Parameters:
removeFrom- the iterator to (potentially) remove elements fromelementsToRetain- the elements to retain- Returns:
trueif any element was removed fromiterator
-
elementsEqual
Determines whether two iterators contain equal elements in the same order. More specifically, this method returnstrueifiterator1anditerator2contain the same number of elements and every element ofiterator1is equal to the corresponding element ofiterator2.Note that this will modify the supplied iterators, since they will have been advanced some number of elements forward.
-
toString
-
getOnlyElement
Returns the single element contained initerator.- Throws:
NoSuchElementException- if the iterator is emptyIllegalArgumentException- if the iterator contains multiple elements. The state of the iterator is unspecified.
-
getOnlyElement
public static <T extends @Nullable Object> T getOnlyElement(Iterator<? extends T> iterator, T defaultValue) Returns the single element contained initerator, ordefaultValueif the iterator is empty.- Throws:
IllegalArgumentException- if the iterator contains multiple elements. The state of the iterator is unspecified.
-
toArray
@GwtIncompatible public static <T extends @Nullable Object> T[] toArray(Iterator<? extends T> iterator, Class<@NonNull T> type) Copies an iterator's elements into an array. The iterator will be left exhausted: itshasNext()method will returnfalse.- Parameters:
iterator- the iterator to copytype- the type of the elements- Returns:
- a newly-allocated array into which all the elements of the iterator have been copied
-
addAll
@CanIgnoreReturnValue public static <T extends @Nullable Object> boolean addAll(Collection<T> addTo, Iterator<? extends T> iterator) Adds all elements initeratortocollection. The iterator will be left exhausted: itshasNext()method will returnfalse.- Returns:
trueifcollectionwas modified as a result of this operation
-
frequency
-
cycle
Returns an iterator that cycles indefinitely over the elements ofiterable.The returned iterator supports
remove()if the provided iterator does. Afterremove()is called, subsequent cycles omit the removed element, which is no longer initerable. The iterator'shasNext()method returnstrueuntiliterableis empty.Warning: Typical uses of the resulting iterator may produce an infinite loop. You should use an explicit
breakor be certain that you will eventually remove all the elements. -
cycle
Returns an iterator that cycles indefinitely over the provided elements.The returned iterator supports
remove(). Afterremove()is called, subsequent cycles omit the removed element, butelementsdoes not change. The iterator'shasNext()method returnstrueuntil all of the original elements have been removed.Warning: Typical uses of the resulting iterator may produce an infinite loop. You should use an explicit
breakor be certain that you will eventually remove all the elements. -
concat
public static <T extends @Nullable Object> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b) Combines two iterators into a single iterator. The returned iterator iterates across the elements ina, followed by the elements inb. The source iterators are not polled until necessary.The returned iterator supports
remove()when the corresponding input iterator supports it. -
concat
public static <T extends @Nullable Object> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b, Iterator<? extends T> c) Combines three iterators into a single iterator. The returned iterator iterates across the elements ina, followed by the elements inb, followed by the elements inc. The source iterators are not polled until necessary.The returned iterator supports
remove()when the corresponding input iterator supports it. -
concat
public static <T extends @Nullable Object> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b, Iterator<? extends T> c, Iterator<? extends T> d) Combines four iterators into a single iterator. The returned iterator iterates across the elements ina, followed by the elements inb, followed by the elements inc, followed by the elements ind. The source iterators are not polled until necessary.The returned iterator supports
remove()when the corresponding input iterator supports it. -
concat
@SafeVarargs public static <T extends @Nullable Object> Iterator<T> concat(Iterator<? extends T>... inputs) Combines multiple iterators into a single iterator. The returned iterator iterates across the elements of each iterator ininputs. The input iterators are not polled until necessary.The returned iterator supports
remove()when the corresponding input iterator supports it.- Throws:
NullPointerException- if any of the provided iterators is null
-
concat
public static <T extends @Nullable Object> Iterator<T> concat(Iterator<? extends Iterator<? extends T>> inputs) Combines multiple iterators into a single iterator. The returned iterator iterates across the elements of each iterator ininputs. The input iterators are not polled until necessary.The returned iterator supports
remove()when the corresponding input iterator supports it. The methods of the returned iterator may throwNullPointerExceptionif any of the input iterators is null. -
partition
public static <T extends @Nullable Object> UnmodifiableIterator<List<T>> partition(Iterator<T> iterator, int size) Divides an iterator into unmodifiable sublists of the given size (the final list may be smaller). For example, partitioning an iterator containing[a, b, c, d, e]with a partition size of 3 yields[[a, b, c], [d, e]]-- an outer iterator containing two inner lists of three and two elements, all in the original order.The returned lists implement
RandomAccess.Note: The current implementation eagerly allocates storage for
sizeelements. As a consequence, passing values likeInteger.MAX_VALUEcan lead toOutOfMemoryError.- Parameters:
iterator- the iterator to return a partitioned view ofsize- the desired size of each partition (the last may be smaller)- Returns:
- an iterator of immutable lists containing the elements of
iteratordivided into partitions - Throws:
IllegalArgumentException- ifsizeis nonpositive
-
paddedPartition
public static <T extends @Nullable Object> UnmodifiableIterator<List<@Nullable T>> paddedPartition(Iterator<T> iterator, int size) Divides an iterator into unmodifiable sublists of the given size, padding the final iterator with null values if necessary. For example, partitioning an iterator containing[a, b, c, d, e]with a partition size of 3 yields[[a, b, c], [d, e, null]]-- an outer iterator containing two inner lists of three elements each, all in the original order.The returned lists implement
RandomAccess.- Parameters:
iterator- the iterator to return a partitioned view ofsize- the desired size of each partition- Returns:
- an iterator of immutable lists containing the elements of
iteratordivided into partitions (the final iterable may have trailing null elements) - Throws:
IllegalArgumentException- ifsizeis nonpositive
-
filter
public static <T extends @Nullable Object> UnmodifiableIterator<T> filter(Iterator<T> unfiltered, Predicate<? super T> retainIfTrue) Returns a view ofunfilteredcontaining all elements that satisfy the input predicateretainIfTrue. -
filter
@GwtIncompatible public static <T> UnmodifiableIterator<T> filter(Iterator<?> unfiltered, Class<T> desiredType) Returns a view ofunfilteredcontaining all elements that are of the typedesiredType. -
any
-
all
-
find
public static <T extends @Nullable Object> T find(Iterator<T> iterator, Predicate<? super T> predicate) Returns the first element initeratorthat satisfies the given predicate; use this method only when such an element is known to exist. If no such element is found, the iterator will be left exhausted: itshasNext()method will returnfalse. If it is possible that no element will match, usetryFind(Iterator, Predicate)orfind(Iterator, Predicate, Object)instead.- Throws:
NoSuchElementException- if no element initeratormatches the given predicate
-
find
public static <T extends @Nullable Object> @Nullable T find(Iterator<? extends T> iterator, Predicate<? super T> predicate, @Nullable T defaultValue) Returns the first element initeratorthat satisfies the given predicate. If no such element is found,defaultValuewill be returned from this method and the iterator will be left exhausted: itshasNext()method will returnfalse. Note that this can usually be handled more naturally usingtryFind(iterator, predicate).or(defaultValue).- Since:
- 7.0
-
tryFind
Returns anOptionalcontaining the first element initeratorthat satisfies the given predicate, if such an element exists. If no such element is found, an emptyOptionalwill be returned from this method and the iterator will be left exhausted: itshasNext()method will returnfalse.Warning: avoid using a
predicatethat matchesnull. Ifnullis matched initerator, a NullPointerException will be thrown.- Since:
- 11.0
-
indexOf
public static <T extends @Nullable Object> int indexOf(Iterator<T> iterator, Predicate<? super T> predicate) Returns the index initeratorof the first element that satisfies the providedpredicate, or-1if the Iterator has no such elements.More formally, returns the lowest index
isuch thatpredicate.apply(Iterators.get(iterator, i))returnstrue, or-1if there is no such index.If -1 is returned, the iterator will be left exhausted: its
hasNext()method will returnfalse. Otherwise, the iterator will be set to the element which satisfies thepredicate.- Since:
- 2.0
-
transform
public static <F extends @Nullable Object, T extends @Nullable Object> Iterator<T> transform(Iterator<F> fromIterator, Function<? super F, ? extends T> function) Returns a view containing the result of applyingfunctionto each element offromIterator.The returned iterator supports
remove()iffromIteratordoes. After a successfulremove()call,fromIteratorno longer contains the corresponding element. -
get
Advancesiteratorposition + 1times, returning the element at thepositionth position.- Parameters:
position- position of the element to return- Returns:
- the element at the specified position in
iterator - Throws:
IndexOutOfBoundsException- ifpositionis negative or greater than or equal to the number of elements remaining initerator
-
get
public static <T extends @Nullable Object> T get(Iterator<? extends T> iterator, int position, T defaultValue) Advancesiteratorposition + 1times, returning the element at thepositionth position ordefaultValueotherwise.- Parameters:
position- position of the element to returndefaultValue- the default value to return if the iterator is empty or ifpositionis greater than the number of elements remaining initerator- Returns:
- the element at the specified position in
iteratorordefaultValueifiteratorproduces fewer thanposition + 1elements. - Throws:
IndexOutOfBoundsException- ifpositionis negative- Since:
- 4.0
-
getNext
public static <T extends @Nullable Object> T getNext(Iterator<? extends T> iterator, T defaultValue) Returns the next element initeratorordefaultValueif the iterator is empty. TheIterablesanalog to this method isIterables.getFirst(Iterable, T).- Parameters:
defaultValue- the default value to return if the iterator is empty- Returns:
- the next element of
iteratoror the default value - Since:
- 7.0
-
getLast
Advancesiteratorto the end, returning the last element.- Returns:
- the last element of
iterator - Throws:
NoSuchElementException- if the iterator is empty
-
getLast
public static <T extends @Nullable Object> T getLast(Iterator<? extends T> iterator, T defaultValue) Advancesiteratorto the end, returning the last element ordefaultValueif the iterator is empty.- Parameters:
defaultValue- the default value to return if the iterator is empty- Returns:
- the last element of
iterator - Since:
- 3.0
-
advance
Callsnext()oniterator, eithernumberToAdvancetimes or untilhasNext()returnsfalse, whichever comes first.- Returns:
- the number of elements the iterator was advanced
- Since:
- 13.0 (since 3.0 as
Iterators.skip)
-
limit
Returns a view containing the firstlimitSizeelements ofiterator. Ifiteratorcontains fewer thanlimitSizeelements, the returned view contains all of its elements. The returned iterator supportsremove()ifiteratordoes.- Parameters:
iterator- the iterator to limitlimitSize- the maximum number of elements in the returned iterator- Throws:
IllegalArgumentException- iflimitSizeis negative- Since:
- 3.0
-
consumingIterator
Returns a view of the suppliediteratorthat removes each element from the suppliediteratoras it is returned.The provided iterator must support
Iterator.remove()or else the returned iterator will fail on the first call tonext. The returnedIteratoris also not thread-safe.- Parameters:
iterator- the iterator to remove and return elements from- Returns:
- an iterator that removes and returns elements from the supplied iterator
- Since:
- 2.0
-
forArray
@SafeVarargs public static <T extends @Nullable Object> UnmodifiableIterator<T> forArray(T... array) Returns an iterator containing the elements ofarrayin order. The returned iterator is a view of the array; subsequent changes to the array will be reflected in the iterator.Note: It is often preferable to represent your data using a collection type, for example using
Arrays.asList(Object[]), making this method unnecessary.The
Iterableequivalent of this method is eitherArrays.asList(Object[]),ImmutableList.copyOf(Object[])}, orImmutableList.of(). -
singletonIterator
Returns an iterator containing onlyvalue.The
Iterableequivalent of this method isCollections.singleton(T). -
forEnumeration
public static <T extends @Nullable Object> UnmodifiableIterator<T> forEnumeration(Enumeration<T> enumeration) Adapts anEnumerationto theIteratorinterface.This method has no equivalent in
Iterablesbecause viewing anEnumerationas anIterableis impossible. However, the contents can be copied into a collection usingCollections.list(Enumeration).Java 9 users: use
enumeration.asIterator()instead, unless it is important to return anUnmodifiableIteratorinstead of a plainIterator. -
asEnumeration
Adapts anIteratorto theEnumerationinterface.The
Iterableequivalent of this method is eitherCollections.enumeration(Collection)(if you have aCollection), orIterators.asEnumeration(collection.iterator()). -
peekingIterator
public static <T extends @Nullable Object> PeekingIterator<T> peekingIterator(Iterator<? extends T> iterator) Returns aPeekingIteratorbacked by the given iterator.Calls to the
peekmethod with no intervening calls tonextdo not affect the iteration, and hence return the same object each time. A subsequent call tonextis guaranteed to return the same object again. For example:PeekingIterator<String> peekingIterator = Iterators.peekingIterator(Iterators.forArray("a", "b")); String a1 = peekingIterator.peek(); // returns "a" String a2 = peekingIterator.peek(); // also returns "a" String a3 = peekingIterator.next(); // also returns "a"Any structural changes to the underlying iteration (aside from those performed by the iterator's own
PeekingIterator.remove()method) will leave the iterator in an undefined state.The returned iterator does not support removal after peeking, as explained by
PeekingIterator.remove().Note: If the given iterator is already a
PeekingIterator, it might be returned to the caller, although this is neither guaranteed to occur nor required to be consistent. For example, this method might choose to pass through recognized implementations ofPeekingIteratorwhen the behavior of the implementation is known to meet the contract guaranteed by this method.There is no
Iterableequivalent to this method, so use this method to wrap each individual iterator as it is generated.- Parameters:
iterator- the backing iterator. ThePeekingIteratorassumes ownership of this iterator, so users should cease making direct calls to it after calling this method.- Returns:
- a peeking iterator backed by that iterator. Apart from the additional
PeekingIterator.peek()method, this iterator behaves exactly the same asiterator.
-
peekingIterator
@InlineMe(replacement="checkNotNull(iterator)", staticImports="com.google.common.base.Preconditions.checkNotNull") @Deprecated public static <T extends @Nullable Object> PeekingIterator<T> peekingIterator(PeekingIterator<T> iterator) Deprecated.no need to use thisSimply returns its argument.- Since:
- 10.0
-
mergeSorted
public static <T extends @Nullable Object> UnmodifiableIterator<T> mergeSorted(Iterable<? extends Iterator<? extends T>> iterators, Comparator<? super T> comparator) Returns an iterator over the merged contents of all giveniterators, traversing every element of the input iterators. Equivalent entries will not be de-duplicated.Callers must ensure that the source
iteratorsare in non-descending order as this method does not sort its input.For any equivalent elements across all
iterators, elements are returned in the order of their source iterators. That is, if element A from iterator 1 and element B from iterator 2 compare as equal, A will be returned before B if iterator 1 was passed before iterator 2.- Since:
- 11.0
-