@GwtCompatible(emulated=true) public final class Iterables extends Object
Iterable. Except as noted, each method has a corresponding Iterator-based method
in the Iterators class.
Java 8 users: several common uses for this class are now more comprehensively addressed
by the new Stream library. Read the method documentation below for
comparisons. This class is not being deprecated, but we gently encourage you to migrate to
streams.
Performance notes: Unless otherwise noted, all of the iterables produced in this class are lazy, which means that their iterators only advance the backing iteration when absolutely necessary.
See the Guava User Guide article on Iterables.
| Modifier and Type | Method and Description |
|---|---|
static <T> boolean |
addAll(Collection<T> addTo,
Iterable<? extends T> elementsToAdd)
Adds all elements in
iterable to collection. |
static <T> boolean |
all(Iterable<T> iterable,
Predicate<? super T> predicate)
Returns
true if every element in iterable satisfies the predicate. |
static <T> boolean |
any(Iterable<T> iterable,
Predicate<? super T> predicate)
Returns
true if any element in iterable satisfies the predicate. |
static <T> Iterable<T> |
concat(Iterable<? extends Iterable<? extends T>> inputs)
Combines multiple iterables into a single iterable.
|
static <T> Iterable<T> |
concat(Iterable<? extends T>... inputs)
Combines multiple iterables into a single iterable.
|
static <T> Iterable<T> |
concat(Iterable<? extends T> a,
Iterable<? extends T> b)
Combines two iterables into a single iterable.
|
static <T> Iterable<T> |
concat(Iterable<? extends T> a,
Iterable<? extends T> b,
Iterable<? extends T> c)
Combines three iterables into a single iterable.
|
static <T> Iterable<T> |
concat(Iterable<? extends T> a,
Iterable<? extends T> b,
Iterable<? extends T> c,
Iterable<? extends T> d)
Combines four iterables into a single iterable.
|
static <T> Iterable<T> |
consumingIterable(Iterable<T> iterable)
Returns a view of the supplied iterable that wraps each generated
Iterator through Iterators.consumingIterator(Iterator). |
static boolean |
contains(Iterable<?> iterable,
Object element)
Returns
true if iterable contains any element o for which Objects.equals(o, element) would return true. |
static <T> Iterable<T> |
cycle(Iterable<T> iterable)
Returns an iterable whose iterators cycle indefinitely over the elements of
iterable. |
static <T> Iterable<T> |
cycle(T... elements)
Returns an iterable whose iterators cycle indefinitely over the provided elements.
|
static boolean |
elementsEqual(Iterable<?> iterable1,
Iterable<?> iterable2)
Determines whether two iterables contain equal elements in the same order.
|
static <T> Iterable<T> |
filter(Iterable<?> unfiltered,
Class<T> desiredType)
Returns a view of
unfiltered containing all elements that are of the type desiredType. |
static <T> Iterable<T> |
filter(Iterable<T> unfiltered,
Predicate<? super T> retainIfTrue)
Returns a view of
unfiltered containing all elements that satisfy the input predicate
retainIfTrue. |
static <T> T |
find(Iterable<? extends T> iterable,
Predicate<? super T> predicate,
T defaultValue)
Returns the first element in
iterable that satisfies the given
predicate, or defaultValue if none found. |
static <T> T |
find(Iterable<T> iterable,
Predicate<? super T> predicate)
Returns the first element in
iterable that satisfies the given
predicate; use this method only when such an element is known to exist. |
static int |
frequency(Iterable<?> iterable,
Object element)
Returns the number of elements in the specified iterable that equal the specified object.
|
static <T> T |
get(Iterable<? extends T> iterable,
int position,
T defaultValue)
Returns the element at the specified position in an iterable or a default
value otherwise.
|
static <T> T |
get(Iterable<T> iterable,
int position)
Returns the element at the specified position in an iterable.
|
static <T> T |
getFirst(Iterable<? extends T> iterable,
T defaultValue)
Returns the first element in
iterable or defaultValue if the iterable is empty. |
static <T> T |
getLast(Iterable<? extends T> iterable,
T defaultValue)
Returns the last element of
iterable or defaultValue if
the iterable is empty. |
static <T> T |
getLast(Iterable<T> iterable)
Returns the last element of
iterable. |
static <T> T |
getOnlyElement(Iterable<? extends T> iterable,
T defaultValue)
Returns the single element contained in
iterable, or defaultValue if the
iterable is empty. |
static <T> T |
getOnlyElement(Iterable<T> iterable)
Returns the single element contained in
iterable. |
static <T> int |
indexOf(Iterable<T> iterable,
Predicate<? super T> predicate)
Returns the index in
iterable of the first element that satisfies
the provided predicate, or -1 if the Iterable has no such
elements. |
static boolean |
isEmpty(Iterable<?> iterable)
Determines if the given iterable contains no elements.
|
static <T> Iterable<T> |
limit(Iterable<T> iterable,
int limitSize)
Returns a view of
iterable containing its first limitSize
elements. |
static <T> Iterable<T> |
mergeSorted(Iterable<? extends Iterable<? extends T>> iterables,
Comparator<? super T> comparator)
Returns an iterable over the merged contents of all given
iterables. |
static <T> Iterable<List<T>> |
paddedPartition(Iterable<T> iterable,
int size)
Divides an iterable into unmodifiable sublists of the given size, padding
the final iterable with null values if necessary.
|
static <T> Iterable<List<T>> |
partition(Iterable<T> iterable,
int size)
Divides an iterable into unmodifiable sublists of the given size (the final
iterable may be smaller).
|
static boolean |
removeAll(Iterable<?> removeFrom,
Collection<?> elementsToRemove)
Removes, from an iterable, every element that belongs to the provided
collection.
|
static <T> boolean |
removeIf(Iterable<T> removeFrom,
Predicate<? super T> predicate)
Removes, from an iterable, every element that satisfies the provided
predicate.
|
static boolean |
retainAll(Iterable<?> removeFrom,
Collection<?> elementsToRetain)
Removes, from an iterable, every element that does not belong to the
provided collection.
|
static int |
size(Iterable<?> iterable)
Returns the number of elements in
iterable. |
static <T> Iterable<T> |
skip(Iterable<T> iterable,
int numberToSkip)
Returns a view of
iterable that skips its first
numberToSkip elements. |
static <T> T[] |
toArray(Iterable<? extends T> iterable,
Class<T> type)
Copies an iterable's elements into an array.
|
static String |
toString(Iterable<?> iterable)
Returns a string representation of
iterable, with the format [e1, e2, ..., en] (that is, identical to Arrays.toString(Iterables.toArray(iterable))). |
static <F,T> Iterable<T> |
transform(Iterable<F> fromIterable,
Function<? super F,? extends T> function)
Returns a view containing the result of applying
function to each
element of fromIterable. |
static <T> Optional<T> |
tryFind(Iterable<T> iterable,
Predicate<? super T> predicate)
Returns an
Optional containing the first element in iterable that satisfies the given predicate, if such an element exists. |
static <E> Iterable<E> |
unmodifiableIterable(ImmutableCollection<E> iterable)
Deprecated.
no need to use this
|
static <T> Iterable<T> |
unmodifiableIterable(Iterable<? extends T> iterable)
Returns an unmodifiable view of
iterable. |
public static <T> Iterable<T> unmodifiableIterable(Iterable<? extends T> iterable)
iterable.@Deprecated public static <E> Iterable<E> unmodifiableIterable(ImmutableCollection<E> iterable)
public static boolean contains(Iterable<?> iterable, @Nullable Object element)
true if iterable contains any element o for which Objects.equals(o, element) would return true. Otherwise returns false, even in
cases where Collection.contains(java.lang.Object) might throw NullPointerException or ClassCastException.public static boolean removeAll(Iterable<?> removeFrom, Collection<?> elementsToRemove)
This method calls Collection.removeAll(java.util.Collection<?>) if iterable is a
collection, and Iterators.removeAll(java.util.Iterator<?>, java.util.Collection<?>) otherwise.
removeFrom - the iterable to (potentially) remove elements fromelementsToRemove - the elements to removetrue if any element was removed from iterablepublic static boolean retainAll(Iterable<?> removeFrom, Collection<?> elementsToRetain)
This method calls Collection.retainAll(java.util.Collection<?>) if iterable is a
collection, and Iterators.retainAll(java.util.Iterator<?>, java.util.Collection<?>) otherwise.
removeFrom - the iterable to (potentially) remove elements fromelementsToRetain - the elements to retaintrue if any element was removed from iterablepublic static <T> boolean removeIf(Iterable<T> removeFrom, Predicate<? super T> predicate)
Removals may or may not happen immediately as each element is tested
against the predicate. The behavior of this method is not specified if
predicate is dependent on removeFrom.
Java 8 users: if removeFrom is a Collection,
use removeFrom.removeIf(predicate) instead.
removeFrom - the iterable to (potentially) remove elements frompredicate - a predicate that determines whether an element should
be removedtrue if any elements were removed from the iterableUnsupportedOperationException - if the iterable does not support
remove().public static boolean elementsEqual(Iterable<?> iterable1, Iterable<?> iterable2)
true if iterable1
and iterable2 contain the same number of elements and every element
of iterable1 is equal to the corresponding element of
iterable2.public static String toString(Iterable<?> iterable)
iterable, with the format [e1, e2, ..., en] (that is, identical to Arrays.toString(Iterables.toArray(iterable))). Note that for
most implementations of Collection, collection.toString() also gives the same result, but that behavior is not
generally guaranteed.public static <T> T getOnlyElement(Iterable<T> iterable)
iterable.
Java 8 users: the Stream equivalent to this method is stream.collect(MoreCollectors.onlyElement()).
NoSuchElementException - if the iterable is emptyIllegalArgumentException - if the iterable contains multiple elements@Nullable public static <T> T getOnlyElement(Iterable<? extends T> iterable, @Nullable T defaultValue)
iterable, or defaultValue if the
iterable is empty.
Java 8 users: the Stream equivalent to this method is stream.collect(MoreCollectors.toOptional()).orElse(defaultValue).
IllegalArgumentException - if the iterator contains multiple elements@GwtIncompatible public static <T> T[] toArray(Iterable<? extends T> iterable, Class<T> type)
iterable - the iterable to copytype - the type of the elementspublic static <T> boolean addAll(Collection<T> addTo, Iterable<? extends T> elementsToAdd)
iterable to collection.true if collection was modified as a result of this
operation.public static int frequency(Iterable<?> iterable, @Nullable Object element)
Multiset or Set.
Java 8 users: In most cases, the Stream equivalent of this method is stream.filter(element::equals).count(). If element might be null, use stream.filter(Predicate.isEqual(element)).count() instead.
public static <T> Iterable<T> cycle(Iterable<T> iterable)
iterable.
That iterator supports remove() if iterable.iterator() does. After remove() is called, subsequent cycles omit the removed element, which is no longer in iterable. The iterator's hasNext() method returns true until iterable
is empty.
Warning: Typical uses of the resulting iterator may produce an infinite loop. You
should use an explicit break or be certain that you will eventually remove all the
elements.
To cycle over the iterable n times, use the following: Iterables.concat(Collections.nCopies(n, iterable))
Java 8 users: The Stream equivalent of this method is Stream.generate(() -> iterable).flatMap(Streams::stream).
@SafeVarargs public static <T> Iterable<T> cycle(T... elements)
After remove is invoked on a generated iterator, the removed element will no longer
appear in either that iterator or any other iterator created from the same source iterable.
That is, this method behaves exactly as Iterables.cycle(Lists.newArrayList(elements)).
The iterator's hasNext method returns true until 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 break or be certain that you will eventually remove all the
elements.
To cycle over the elements n times, use the following: Iterables.concat(Collections.nCopies(n, Arrays.asList(elements)))
Java 8 users: If passing a single element e, the Stream equivalent of
this method is Stream.generate(() -> e). Otherwise, put the elements in a collection
and use Stream.generate(() -> collection).flatMap(Collection::stream).
public static <T> Iterable<T> concat(Iterable<? extends T> a, Iterable<? extends T> b)
a, followed by the elements in b. The source
iterators are not polled until necessary.
The returned iterable's iterator supports remove() when the corresponding input
iterator supports it.
Java 8 users: The Stream equivalent of this method is Stream.concat(a, b).
public static <T> Iterable<T> concat(Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c)
a, followed by the elements in b, followed by the
elements in c. The source iterators are not polled until necessary.
The returned iterable's iterator supports remove() when the corresponding input
iterator supports it.
Java 8 users: The Stream equivalent of this method is Streams.concat(a, b, c).
public static <T> Iterable<T> concat(Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c, Iterable<? extends T> d)
a, followed by the elements in b, followed by the
elements in c, followed by the elements in d. The source iterators are not
polled until necessary.
The returned iterable's iterator supports remove() when the corresponding input
iterator supports it.
Java 8 users: The Stream equivalent of this method is Streams.concat(a, b, c, d).
@SafeVarargs public static <T> Iterable<T> concat(Iterable<? extends T>... inputs)
inputs. The input iterators are not polled
until necessary.
The returned iterable's iterator supports remove() when the corresponding input
iterator supports it.
Java 8 users: The Stream equivalent of this method is Streams.concat(...).
NullPointerException - if any of the provided iterables is nullpublic static <T> Iterable<T> concat(Iterable<? extends Iterable<? extends T>> inputs)
inputs. The input iterators are not polled
until necessary.
The returned iterable's iterator supports remove() when the corresponding input
iterator supports it. The methods of the returned iterable may throw NullPointerException if any of the input iterators is null.
Java 8 users: The Stream equivalent of this method is streamOfStreams.flatMap(s -> s).
public static <T> Iterable<List<T>> partition(Iterable<T> iterable, int size)
[a, b, c, d, e] with a partition size of 3 yields [[a, b, c], [d, e]] -- an outer iterable containing two inner lists of
three and two elements, all in the original order.
Iterators returned by the returned iterable do not support the Iterator.remove() method. The returned lists implement RandomAccess, whether or not the input list does.
Note: if iterable is a List, use Lists.partition(List, int) instead.
iterable - the iterable to return a partitioned view ofsize - the desired size of each partition (the last may be smaller)iterable divided into partitionsIllegalArgumentException - if size is nonpositivepublic static <T> Iterable<List<T>> paddedPartition(Iterable<T> iterable, int size)
[a, b, c, d, e] with a partition size of 3
yields [[a, b, c], [d, e, null]] -- an outer iterable containing
two inner lists of three elements each, all in the original order.
Iterators returned by the returned iterable do not support the Iterator.remove() method.
iterable - the iterable to return a partitioned view ofsize - the desired size of each partitioniterable divided into partitions (the final iterable may have
trailing null elements)IllegalArgumentException - if size is nonpositivepublic static <T> Iterable<T> filter(Iterable<T> unfiltered, Predicate<? super T> retainIfTrue)
unfiltered containing all elements that satisfy the input predicate
retainIfTrue. The returned iterable's iterator does not support remove().
Stream equivalent: Stream.filter(java.util.function.Predicate<? super T>).
@GwtIncompatible public static <T> Iterable<T> filter(Iterable<?> unfiltered, Class<T> desiredType)
unfiltered containing all elements that are of the type desiredType. The returned iterable's iterator does not support remove().
Stream equivalent: stream.filter(type::isInstance).map(type::cast).
This does perform a little more work than necessary, so another option is to insert an
unchecked cast at some later point:
@SuppressWarnings("unchecked") // safe because of ::isInstance check
ImmutableList<NewType> result =
(ImmutableList) stream.filter(NewType.class::isInstance).collect(toImmutableList());
public static <T> boolean any(Iterable<T> iterable, Predicate<? super T> predicate)
true if any element in iterable satisfies the predicate.
Stream equivalent: Stream.anyMatch(java.util.function.Predicate<? super T>).
public static <T> boolean all(Iterable<T> iterable, Predicate<? super T> predicate)
true if every element in iterable satisfies the predicate. If iterable is empty, true is returned.
Stream equivalent: Stream.allMatch(java.util.function.Predicate<? super T>).
public static <T> T find(Iterable<T> iterable, Predicate<? super T> predicate)
iterable that satisfies the given
predicate; use this method only when such an element is known to exist. If
it is possible that no element will match, use tryFind(java.lang.Iterable<T>, com.google.common.base.Predicate<? super T>) or
find(Iterable, Predicate, Object) instead.
Stream equivalent: stream.filter(predicate).findFirst().get()
NoSuchElementException - if no element in iterable matches
the given predicate@Nullable public static <T> T find(Iterable<? extends T> iterable, Predicate<? super T> predicate, @Nullable T defaultValue)
iterable that satisfies the given
predicate, or defaultValue if none found. Note that this can
usually be handled more naturally using tryFind(iterable, predicate).or(defaultValue).
Stream equivalent:
stream.filter(predicate).findFirst().orElse(defaultValue)
public static <T> Optional<T> tryFind(Iterable<T> iterable, Predicate<? super T> predicate)
Optional containing the first element in iterable that satisfies the given predicate, if such an element exists.
Warning: avoid using a predicate that matches null. If null is matched in iterable, a
NullPointerException will be thrown.
Stream equivalent:
stream.filter(predicate).findFirst()
public static <T> int indexOf(Iterable<T> iterable, Predicate<? super T> predicate)
iterable of the first element that satisfies
the provided predicate, or -1 if the Iterable has no such
elements.
More formally, returns the lowest index i such that
predicate.apply(Iterables.get(iterable, i)) returns true,
or -1 if there is no such index.
public static <F,T> Iterable<T> transform(Iterable<F> fromIterable, Function<? super F,? extends T> function)
function to each
element of fromIterable.
The returned iterable's iterator supports remove() if fromIterable's iterator does. After a successful remove() call,
fromIterable no longer contains the corresponding element.
If the input Iterable is known to be a List or other
Collection, consider Lists.transform(java.util.List<F>, com.google.common.base.Function<? super F, ? extends T>) and Collections2.transform(java.util.Collection<F>, com.google.common.base.Function<? super F, T>).
Stream equivalent: Stream.map(java.util.function.Function<? super T, ? extends R>)
public static <T> T get(Iterable<T> iterable, int position)
Stream equivalent: stream.skip(position).findFirst().get()
(throws NoSuchElementException if out of bounds)
position - position of the element to returniterableIndexOutOfBoundsException - if position is negative or
greater than or equal to the size of iterable@Nullable public static <T> T get(Iterable<? extends T> iterable, int position, @Nullable T defaultValue)
Stream equivalent:
stream.skip(position).findFirst().orElse(defaultValue)
(returns the default value if the index is out of bounds)
position - position of the element to returndefaultValue - the default value to return if position is
greater than or equal to the size of the iterableiterable or
defaultValue if iterable contains fewer than
position + 1 elements.IndexOutOfBoundsException - if position is negative@Nullable public static <T> T getFirst(Iterable<? extends T> iterable, @Nullable T defaultValue)
iterable or defaultValue if the iterable is empty.
The Iterators analog to this method is Iterators.getNext(java.util.Iterator<? extends T>, T).
If no default value is desired (and the caller instead wants a NoSuchElementException to be thrown), it is recommended that iterable.iterator().next() is used instead.
To get the only element in a single-element Iterable, consider using getOnlyElement(Iterable) or getOnlyElement(Iterable, Object) instead.
Stream equivalent: stream.findFirst().orElse(defaultValue)
defaultValue - the default value to return if the iterable is emptyiterable or the default valuepublic static <T> T getLast(Iterable<T> iterable)
iterable. If iterable is a List with
RandomAccess support, then this operation is guaranteed to be O(1).
Stream equivalent: Streams.findLast(stream).get()
iterableNoSuchElementException - if the iterable is empty@Nullable public static <T> T getLast(Iterable<? extends T> iterable, @Nullable T defaultValue)
iterable or defaultValue if
the iterable is empty. If iterable is a List with
RandomAccess support, then this operation is guaranteed to be O(1).
Stream equivalent: Streams.findLast(stream).orElse(defaultValue)
defaultValue - the value to return if iterable is emptyiterable or the default valuepublic static <T> Iterable<T> skip(Iterable<T> iterable, int numberToSkip)
iterable that skips its first
numberToSkip elements. If iterable contains fewer than
numberToSkip elements, the returned iterable skips all of its
elements.
Modifications to the underlying Iterable before a call to
iterator() are reflected in the returned iterator. That is, the
iterator skips the first numberToSkip elements that exist when the
Iterator is created, not when skip() is called.
The returned iterable's iterator supports remove() if the
iterator of the underlying iterable supports it. Note that it is
not possible to delete the last skipped element by immediately
calling remove() on that iterator, as the Iterator
contract states that a call to remove() before a call to
next() will throw an IllegalStateException.
Stream equivalent: Stream.skip(long)
public static <T> Iterable<T> limit(Iterable<T> iterable, int limitSize)
iterable containing its first limitSize
elements. If iterable contains fewer than limitSize
elements, the returned view contains all of its elements. The returned
iterable's iterator supports remove() if iterable's
iterator does.
Stream equivalent: Stream.limit(long)
iterable - the iterable to limitlimitSize - the maximum number of elements in the returned iterableIllegalArgumentException - if limitSize is negativepublic static <T> Iterable<T> consumingIterable(Iterable<T> iterable)
Iterator through Iterators.consumingIterator(Iterator).
Note: If iterable is a Queue, the returned iterable will
get entries from Queue.remove() since Queue's iteration
order is undefined. Calling Iterator.hasNext() on a generated
iterator from the returned iterable may cause an item to be immediately
dequeued for return on a subsequent call to Iterator.next().
iterable - the iterable to wrapIterators.consumingIterator(Iterator); for queues,
an iterable that generates iterators that return and consume the
queue's elements in queue orderIterators.consumingIterator(Iterator)public static boolean isEmpty(Iterable<?> iterable)
There is no precise Iterator equivalent to this method, since
one can only ask an iterator whether it has any elements remaining
(which one does using Iterator.hasNext()).
Stream equivalent: !stream.findAny().isPresent()
true if the iterable contains no elements@Beta public static <T> Iterable<T> mergeSorted(Iterable<? extends Iterable<? extends T>> iterables, Comparator<? super T> comparator)
iterables. Equivalent entries will not be de-duplicated.
Callers must ensure that the source iterables are in
non-descending order as this method does not sort its input.
For any equivalent elements across all iterables, it is
undefined which element is returned first.
Copyright © 2010–2017. All rights reserved.