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 TypeMethodDescriptionstatic <T> booleanaddAll(Collection<T> addTo, Iterator<? extends T> iterator) Adds all elements initeratortocollection.static intCallsnext()oniterator, eithernumberToAdvancetimes or untilhasNext()returnsfalse, whichever comes first.static <T> booleanReturnstrueif every element returned byiteratorsatisfies the given predicate.static <T> booleanReturnstrueif one or more elements returned byiteratorsatisfy the given predicate.static <T> Enumeration<T>asEnumeration(Iterator<T> iterator) Adapts anIteratorto theEnumerationinterface.static <T> Iterator<T>consumingIterator(Iterator<T> iterator) Returns a view of the suppliediteratorthat removes each element from the suppliediteratoras it is returned.static booleanReturnstrueifiteratorcontainselement.static booleanelementsEqual(Iterator<?> iterator1, Iterator<?> iterator2) Determines whether two iterators contain equal elements in the same order.static <T> @Nullable TReturns the first element initeratorthat satisfies the given predicate.static <T> TReturns the first element initeratorthat satisfies the given predicate; use this method only when such an element is known to exist.static <T> UnmodifiableIterator<T>forArray(T... array) Returns an iterator containing the elements ofarrayin order.static <T> UnmodifiableIterator<T>forEnumeration(Enumeration<T> enumeration) Adapts anEnumerationto theIteratorinterface.static intReturns the number of elements in the specified iterator that equal the specified object.static <T> @Nullable TAdvancesiteratorposition + 1times, returning the element at thepositionth position ordefaultValueotherwise.static <T> TAdvancesiteratorposition + 1times, returning the element at thepositionth position.static <T> @Nullable TAdvancesiteratorto the end, returning the last element ordefaultValueif the iterator is empty.static <T> TAdvancesiteratorto the end, returning the last element.static <T> @Nullable TReturns the next element initeratorordefaultValueif the iterator is empty.static <T> @Nullable TgetOnlyElement(Iterator<? extends T> iterator, @Nullable T defaultValue) Returns the single element contained initerator, ordefaultValueif the iterator is empty.static <T> TgetOnlyElement(Iterator<T> iterator) Returns the single element contained initerator.static <T> intReturns the index initeratorof the first element that satisfies the providedpredicate, or-1if the Iterator has no such elements.static <T> Iterator<T>Returns a view containing the firstlimitSizeelements ofiterator.static <T> UnmodifiableIterator<List<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> UnmodifiableIterator<List<T>>Divides an iterator into unmodifiable sublists of the given size (the final list may be smaller).static booleanremoveAll(Iterator<?> removeFrom, Collection<?> elementsToRemove) Traverses an iterator and removes every element that belongs to the provided collection.static <T> booleanRemoves 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> UnmodifiableIterator<T>singletonIterator(@Nullable T value) Returns an iterator containing onlyvalue.static intReturns the number of elements remaining initerator.static StringReturns a string representation ofiterator, with the format[e1, e2, ..., en].static <T> UnmodifiableIterator<T>unmodifiableIterator(Iterator<? extends T> iterator) Returns an unmodifiable view ofiterator.static <T> UnmodifiableIterator<T>unmodifiableIterator(UnmodifiableIterator<T> iterator) Deprecated.no need to use this
-
Method Details
-
unmodifiableIterator
Returns an unmodifiable view ofiterator. -
unmodifiableIterator
@Deprecated public static <T> 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
Returnstrueifiteratorcontainselement. -
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> 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
Returns a string representation ofiterator, with the format[e1, e2, ..., en]. The iterator will be left exhausted: itshasNext()method will returnfalse. -
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> @Nullable T getOnlyElement(Iterator<? extends T> iterator, @Nullable 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.
-
addAll
@CanIgnoreReturnValue public static <T> 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
Returns the number of elements in the specified iterator that equal the specified object. The iterator will be left exhausted: itshasNext()method will returnfalse. -
partition
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.- 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
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
-
any
Returnstrueif one or more elements returned byiteratorsatisfy the given predicate. -
all
Returnstrueif every element returned byiteratorsatisfies the given predicate. Ifiteratoris empty,trueis returned. -
find
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, use#tryFindorfind(Iterator, Predicate, Object)instead.- Throws:
NoSuchElementException- if no element initeratormatches the given predicate
-
find
public static <T> @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
-
indexOf
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
-
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> @Nullable T get(Iterator<? extends T> iterator, int position, @Nullable 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
Returns the next element initeratorordefaultValueif the iterator is empty. TheIterablesanalog to this method isIterables#getFirst.- 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
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.- 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
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
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(java.util.Enumeration<T>). -
asEnumeration
Adapts anIteratorto theEnumerationinterface.The
Iterableequivalent of this method is eitherCollections.enumeration(java.util.Collection<T>)(if you have aCollection), orIterators.asEnumeration(collection.iterator()).
-