Class FluentIterable<E>
- java.lang.Object
-
- com.google.common.collect.FluentIterable<E>
-
- All Implemented Interfaces:
java.lang.Iterable<E>
@GwtCompatible(emulated=true) public abstract class FluentIterable<E> extends java.lang.Object implements java.lang.Iterable<E>
An expandedIterable
API, providing functionality similar to Java 8's powerful streams library in a slightly different way.The following types of methods are provided:
- chaining methods which return a new
FluentIterable
based in some way on the contents of the current one (for exampletransform(com.google.common.base.Function<? super E, T>)
) - element extraction methods which facilitate the retrieval of certain elements (for example
last()
) - query methods which answer questions about the
FluentIterable
's contents (for exampleanyMatch(com.google.common.base.Predicate<? super E>)
) - conversion methods which copy the
FluentIterable
's contents into a new collection or array (for exampletoList()
)
Several lesser-used features are currently available only as static methods on the
Iterables
class.Comparison to streams
Starting with Java 8, the core Java class libraries provide a new "Streams" library (in
java.util.stream
), which is similar toFluentIterable
but generally more powerful. Key differences include:- A stream is single-use; it becomes invalid as soon as any "terminal operation" such as
findFirst()
oriterator()
is invoked. (Even thoughStream
contains all the right method signatures to implementIterable
, it does not actually do so, to avoid implying repeat-iterability.)FluentIterable
, on the other hand, is multiple-use, and does implementIterable
. - Streams offer many features not found here, including
min/max
,distinct
,reduce
,sorted
, the very powerfulcollect
, and built-in support for parallelizing stream operations. FluentIterable
contains several features not available onStream
, which are noted in the method descriptions below.- Streams include primitive-specialized variants such as
IntStream
, the use of which is strongly recommended. - Streams are standard Java, not requiring a third-party dependency (but do render your code incompatible with Java 7 and earlier).
Example
Here is an example that accepts a list from a database call, filters it based on a predicate, transforms it by invoking
toString()
on each element, and returns the first 10 elements as aList
:List<String> results = FluentIterable.from(database.getClientList()) .filter(activeInLastMonthPredicate) .transform(Functions.toStringFunction()) .limit(10) .toList();
List<String> results = database.getClientList() .stream() .filter(activeInLastMonthPredicate) .map(Functions.toStringFunction()) .limit(10) .collect(Collectors.toList());
- Since:
- 12.0
- Author:
- Marcin Mikosik
-
-
Constructor Summary
Constructors Modifier Constructor Description protected
FluentIterable()
Constructor for use by subclasses.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description boolean
allMatch(Predicate<? super E> predicate)
Returnstrue
if every element in this fluent iterable satisfies the predicate.boolean
anyMatch(Predicate<? super E> predicate)
Returnstrue
if any element in this fluent iterable satisfies the predicate.FluentIterable<E>
append(E... elements)
Returns a fluent iterable whose iterators traverse first the elements of this fluent iterable, followed byelements
.FluentIterable<E>
append(java.lang.Iterable<? extends E> other)
Returns a fluent iterable whose iterators traverse first the elements of this fluent iterable, followed by those ofother
.boolean
contains(java.lang.Object target)
Returnstrue
if this fluent iterable contains any object for whichequals(target)
is true.<C extends java.util.Collection<? super E>>
CcopyInto(C collection)
Copies all the elements from this fluent iterable tocollection
.FluentIterable<E>
cycle()
Returns a fluent iterable whoseIterator
cycles indefinitely over the elements of this fluent iterable.FluentIterable<E>
filter(Predicate<? super E> predicate)
Returns the elements from this fluent iterable that satisfy a predicate.<T> FluentIterable<T>
filter(java.lang.Class<T> type)
Returns the elements from this fluent iterable that are instances of classtype
.Optional<E>
first()
Returns anOptional
containing the first element in this fluent iterable.Optional<E>
firstMatch(Predicate<? super E> predicate)
Returns anOptional
containing the first element in this fluent iterable that satisfies the given predicate, if such an element exists.static <E> FluentIterable<E>
from(FluentIterable<E> iterable)
Deprecated.instances ofFluentIterable
don't need to be converted toFluentIterable
static <E> FluentIterable<E>
from(java.lang.Iterable<E> iterable)
Returns a fluent iterable that wrapsiterable
, oriterable
itself if it is already aFluentIterable
.E
get(int position)
Returns the element at the specified position in this fluent iterable.<K> ImmutableListMultimap<K,E>
index(Function<? super E,K> keyFunction)
Creates an indexImmutableListMultimap
that contains the results of applying a specified function to each item in thisFluentIterable
of values.boolean
isEmpty()
Determines whether this fluent iterable is empty.java.lang.String
join(Joiner joiner)
Returns aString
containing all of the elements of this fluent iterable joined withjoiner
.Optional<E>
last()
Returns anOptional
containing the last element in this fluent iterable.FluentIterable<E>
limit(int maxSize)
Creates a fluent iterable with the firstsize
elements of this fluent iterable.static <E> FluentIterable<E>
of(E[] elements)
Returns a fluent iterable containingelements
in the specified order.int
size()
Returns the number of elements in this fluent iterable.FluentIterable<E>
skip(int numberToSkip)
Returns a view of this fluent iterable that skips its firstnumberToSkip
elements.E[]
toArray(java.lang.Class<E> type)
Returns an array containing all of the elements from this fluent iterable in iteration order.ImmutableList<E>
toList()
Returns anImmutableList
containing all of the elements from this fluent iterable in proper sequence.<V> ImmutableMap<E,V>
toMap(Function<? super E,V> valueFunction)
Returns an immutable map whose keys are the distinct elements of thisFluentIterable
and whose value for each key was computed byvalueFunction
.ImmutableMultiset<E>
toMultiset()
Returns anImmutableMultiset
containing all of the elements from this fluent iterable.ImmutableSet<E>
toSet()
Returns anImmutableSet
containing all of the elements from this fluent iterable with duplicates removed.ImmutableList<E>
toSortedList(java.util.Comparator<? super E> comparator)
Returns anImmutableList
containing all of the elements from thisFluentIterable
in the order specified bycomparator
.ImmutableSortedSet<E>
toSortedSet(java.util.Comparator<? super E> comparator)
Returns anImmutableSortedSet
containing all of the elements from thisFluentIterable
in the order specified bycomparator
, with duplicates (determined bycomparator.compare(x, y) == 0
) removed.java.lang.String
toString()
Returns a string representation of this fluent iterable, with the format[e1, e2, ..., en]
.<T> FluentIterable<T>
transform(Function<? super E,T> function)
Returns a fluent iterable that appliesfunction
to each element of this fluent iterable.<T> FluentIterable<T>
transformAndConcat(Function<? super E,? extends java.lang.Iterable<? extends T>> function)
Appliesfunction
to each element of this fluent iterable and returns a fluent iterable with the concatenated combination of results.<K> ImmutableMap<K,E>
uniqueIndex(Function<? super E,K> keyFunction)
Returns a map with the contents of thisFluentIterable
as itsvalues
, indexed by keys derived from those values.
-
-
-
Method Detail
-
from
@CheckReturnValue public static <E> FluentIterable<E> from(java.lang.Iterable<E> iterable)
Returns a fluent iterable that wrapsiterable
, oriterable
itself if it is already aFluentIterable
.Stream
equivalent:iterable.stream()
ifiterable
is aCollection
;StreamSupport.stream(iterable.spliterator(), false)
otherwise.
-
from
@Deprecated @CheckReturnValue public static <E> FluentIterable<E> from(FluentIterable<E> iterable)
Deprecated.instances ofFluentIterable
don't need to be converted toFluentIterable
Construct a fluent iterable from another fluent iterable. This is obviously never necessary, but is intended to help call out cases where one migration fromIterable
toFluentIterable
has obviated the need to explicitly convert to aFluentIterable
.
-
of
@Beta @CheckReturnValue public static <E> FluentIterable<E> of(E[] elements)
Returns a fluent iterable containingelements
in the specified order.Stream
equivalent:Stream.of(elements)
orArrays.stream(elements)
.- Since:
- 18.0
-
toString
@CheckReturnValue public java.lang.String toString()
Returns a string representation of this fluent iterable, with the format[e1, e2, ..., en]
.Stream
equivalent:stream.collect(Collectors.joining(", ", "[", "]"))
or (less efficiently)collect(Collectors.toList()).toString()
.- Overrides:
toString
in classjava.lang.Object
-
size
@CheckReturnValue public final int size()
Returns the number of elements in this fluent iterable.Stream
equivalent:stream.count()
.
-
contains
@CheckReturnValue public final boolean contains(@Nullable java.lang.Object target)
Returnstrue
if this fluent iterable contains any object for whichequals(target)
is true.Stream
equivalent:stream.anyMatch(Predicate.isEqual(target))
.
-
cycle
@CheckReturnValue public final FluentIterable<E> cycle()
Returns a fluent iterable whoseIterator
cycles indefinitely over the elements of this fluent iterable.That iterator supports
remove()
ifiterable.iterator()
does. Afterremove()
is called, subsequent cycles omit the removed element, which is no longer in this fluent iterable. The iterator'shasNext()
method returnstrue
until this fluent 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.Stream
equivalent: if the source iterable has only a single elementelement
, useStream.generate(() -> element)
. Otherwise, if the source iterable has astream
method (for example, if it is aCollection
), useStream.generate(iterable::stream).flatMap(s -> s)
.
-
append
@Beta @CheckReturnValue public final FluentIterable<E> append(java.lang.Iterable<? extends E> other)
Returns a fluent iterable whose iterators traverse first the elements of this fluent iterable, followed by those ofother
. The iterators are not polled until necessary.The returned iterable's
Iterator
supportsremove()
when the correspondingIterator
supports it.Stream
equivalent:Stream.concat(thisStream, otherStream)
.- Since:
- 18.0
-
append
@Beta @CheckReturnValue public final FluentIterable<E> append(E... elements)
Returns a fluent iterable whose iterators traverse first the elements of this fluent iterable, followed byelements
.Stream
equivalent:Stream.concat(thisStream, Stream.of(elements))
.- Since:
- 18.0
-
filter
@CheckReturnValue public final FluentIterable<E> filter(Predicate<? super E> predicate)
Returns the elements from this fluent iterable that satisfy a predicate. The resulting fluent iterable's iterator does not supportremove()
.Stream
equivalent:stream.filter(predicate)
(same).
-
filter
@GwtIncompatible("Class.isInstance") @CheckReturnValue public final <T> FluentIterable<T> filter(java.lang.Class<T> type)
Returns the elements from this fluent iterable that are instances of classtype
.- Parameters:
type
- the type of elements desiredStream
equivalent:{@code
-
anyMatch
@CheckReturnValue public final boolean anyMatch(Predicate<? super E> predicate)
Returnstrue
if any element in this fluent iterable satisfies the predicate.Stream
equivalent:stream.anyMatch(predicate)
(same).
-
allMatch
@CheckReturnValue public final boolean allMatch(Predicate<? super E> predicate)
Returnstrue
if every element in this fluent iterable satisfies the predicate. If this fluent iterable is empty,true
is returned.Stream
equivalent:stream.allMatch(predicate)
(same).
-
firstMatch
@CheckReturnValue public final Optional<E> firstMatch(Predicate<? super E> predicate)
Returns anOptional
containing the first element in this fluent iterable that satisfies the given predicate, if such an element exists.Warning: avoid using a
predicate
that matchesnull
. Ifnull
is matched in this fluent iterable, aNullPointerException
will be thrown.Stream
equivalent:stream.filter(predicate).findFirst()
.
-
transform
@CheckReturnValue public final <T> FluentIterable<T> transform(Function<? super E,T> function)
Returns a fluent iterable that appliesfunction
to each element of this fluent iterable.The returned fluent iterable's iterator supports
remove()
if this iterable's iterator does. After a successfulremove()
call, this fluent iterable no longer contains the corresponding element.Stream
equivalent:stream.map(function)
.
-
transformAndConcat
@CheckReturnValue public <T> FluentIterable<T> transformAndConcat(Function<? super E,? extends java.lang.Iterable<? extends T>> function)
Appliesfunction
to each element of this fluent iterable and returns a fluent iterable with the concatenated combination of results.function
returns an Iterable of results.The returned fluent iterable's iterator supports
remove()
if this function-returned iterables' iterator does. After a successfulremove()
call, the returned fluent iterable no longer contains the corresponding element.Stream
equivalent:stream.flatMap(function)
(using a function that produces streams, not iterables).- Since:
- 13.0 (required
Function<E, Iterable<T>>
until 14.0)
-
first
@CheckReturnValue public final Optional<E> first()
Returns anOptional
containing the first element in this fluent iterable. If the iterable is empty,Optional.absent()
is returned.Stream
equivalent: if the goal is to obtain any element,stream.findAny()
; if it must specifically be the first element,stream.findFirst()
.- Throws:
java.lang.NullPointerException
- if the first element is null; if this is a possibility, useiterator().next()
orIterables.getFirst(java.lang.Iterable<? extends T>, T)
instead.
-
last
@CheckReturnValue public final Optional<E> last()
Returns anOptional
containing the last element in this fluent iterable. If the iterable is empty,Optional.absent()
is returned.Stream
equivalent:stream.reduce((a, b) -> b)
.- Throws:
java.lang.NullPointerException
- if the last element is null; if this is a possibility, useIterables.getLast(java.lang.Iterable<T>)
instead.
-
skip
@CheckReturnValue public final FluentIterable<E> skip(int numberToSkip)
Returns a view of this fluent iterable that skips its firstnumberToSkip
elements. If this fluent iterable contains fewer thannumberToSkip
elements, the returned fluent iterable skips all of its elements.Modifications to this fluent iterable before a call to
iterator()
are reflected in the returned fluent iterable. That is, the its iterator skips the firstnumberToSkip
elements that exist when the iterator is created, not whenskip()
is called.The returned fluent iterable's iterator supports
remove()
if theIterator
of this fluent iterable supports it. Note that it is not possible to delete the last skipped element by immediately callingremove()
on the returned fluent iterable's iterator, as theIterator
contract states that a call to* remove()
before a call tonext()
will throw anIllegalStateException
.Stream
equivalent:stream.skip(numberToSkip)
(same).
-
limit
@CheckReturnValue public final FluentIterable<E> limit(int maxSize)
Creates a fluent iterable with the firstsize
elements of this fluent iterable. If this fluent iterable does not contain that many elements, the returned fluent iterable will have the same behavior as this fluent iterable. The returned fluent iterable's iterator supportsremove()
if this fluent iterable's iterator does.Stream
equivalent:stream.limit(maxSize)
(same).- Parameters:
maxSize
- the maximum number of elements in the returned fluent iterable- Throws:
java.lang.IllegalArgumentException
- ifsize
is negative
-
isEmpty
@CheckReturnValue public final boolean isEmpty()
Determines whether this fluent iterable is empty.Stream
equivalent:!stream.findAny().isPresent()
.
-
toList
@CheckReturnValue public final ImmutableList<E> toList()
Returns anImmutableList
containing all of the elements from this fluent iterable in proper sequence.Stream
equivalent:ImmutableList.copyOf(stream.iterator())
.- Since:
- 14.0 (since 12.0 as
toImmutableList()
).
-
toSortedList
@CheckReturnValue public final ImmutableList<E> toSortedList(java.util.Comparator<? super E> comparator)
Returns anImmutableList
containing all of the elements from thisFluentIterable
in the order specified bycomparator
. To produce anImmutableList
sorted by its natural ordering, usetoSortedList(Ordering.natural())
.Stream
equivalent:ImmutableList.copyOf(stream.sorted(comparator).iterator())
.- Parameters:
comparator
- the function by which to sort list elements- Throws:
java.lang.NullPointerException
- if any element is null- Since:
- 14.0 (since 13.0 as
toSortedImmutableList()
).
-
toSet
@CheckReturnValue public final ImmutableSet<E> toSet()
Returns anImmutableSet
containing all of the elements from this fluent iterable with duplicates removed.Stream
equivalent:ImmutableSet.copyOf(stream.iterator())
.- Since:
- 14.0 (since 12.0 as
toImmutableSet()
).
-
toSortedSet
@CheckReturnValue public final ImmutableSortedSet<E> toSortedSet(java.util.Comparator<? super E> comparator)
Returns anImmutableSortedSet
containing all of the elements from thisFluentIterable
in the order specified bycomparator
, with duplicates (determined bycomparator.compare(x, y) == 0
) removed. To produce anImmutableSortedSet
sorted by its natural ordering, usetoSortedSet(Ordering.natural())
.Stream
equivalent:ImmutableSortedSet.copyOf(comparator, stream.iterator())
.- Parameters:
comparator
- the function by which to sort set elements- Throws:
java.lang.NullPointerException
- if any element is null- Since:
- 14.0 (since 12.0 as
toImmutableSortedSet()
).
-
toMultiset
@CheckReturnValue public final ImmutableMultiset<E> toMultiset()
Returns anImmutableMultiset
containing all of the elements from this fluent iterable.Stream
equivalent:ImmutableMultiset.copyOf(stream.iterator())
.- Since:
- 19.0
-
toMap
@CheckReturnValue public final <V> ImmutableMap<E,V> toMap(Function<? super E,V> valueFunction)
Returns an immutable map whose keys are the distinct elements of thisFluentIterable
and whose value for each key was computed byvalueFunction
. The map's iteration order is the order of the first appearance of each key in this iterable.When there are multiple instances of a key in this iterable, it is unspecified whether
valueFunction
will be applied to more than one instance of that key and, if it is, which result will be mapped to that key in the returned map.Stream
equivalent:ImmutableMap.copyOf(stream.collect(Collectors.toMap(k -> k, valueFunction)))
(but note that this may not preserve the order of entries).- Throws:
java.lang.NullPointerException
- if any element of this iterable isnull
, or ifvalueFunction
producesnull
for any key- Since:
- 14.0
-
index
@CheckReturnValue public final <K> ImmutableListMultimap<K,E> index(Function<? super E,K> keyFunction)
Creates an indexImmutableListMultimap
that contains the results of applying a specified function to each item in thisFluentIterable
of values. Each element of this iterable will be stored as a value in the resulting multimap, yielding a multimap with the same size as this iterable. The key used to store that value in the multimap will be the result of calling the function on that value. The resulting multimap is created as an immutable snapshot. In the returned multimap, keys appear in the order they are first encountered, and the values corresponding to each key appear in the same order as they are encountered.- Parameters:
keyFunction
- the function used to produce the key for each value- Throws:
java.lang.NullPointerException
- if any of the following cases is true:keyFunction
is null- An element in this fluent iterable is null
keyFunction
returnsnull
for any element of this iterable
Stream
equivalent:stream.collect(Collectors.groupingBy(keyFunction))
behaves similarly, but returns a mutableMap<K, List<E>>
instead, and may not preserve the order of entries).- Since:
- 14.0
-
uniqueIndex
@CheckReturnValue public final <K> ImmutableMap<K,E> uniqueIndex(Function<? super E,K> keyFunction)
Returns a map with the contents of thisFluentIterable
as itsvalues
, indexed by keys derived from those values. In other words, each input value produces an entry in the map whose key is the result of applyingkeyFunction
to that value. These entries appear in the same order as they appeared in this fluent iterable. Example usage:Color red = new Color("red", 255, 0, 0); ... FluentIterable<Color> allColors = FluentIterable.from(ImmutableSet.of(red, green, blue)); Map<String, Color> colorForName = allColors.uniqueIndex(toStringFunction()); assertThat(colorForName).containsEntry("red", red);
If your index may associate multiple values with each key, use
index
.Stream
equivalent:ImmutableMap.copyOf(stream.collect(Collectors.toMap(keyFunction, v -> v)))
(but note that this may not preserve the order of entries).- Parameters:
keyFunction
- the function used to produce the key for each value- Returns:
- a map mapping the result of evaluating the function
keyFunction
on each value in this fluent iterable to that value - Throws:
java.lang.IllegalArgumentException
- ifkeyFunction
produces the same key for more than one value in this fluent iterablejava.lang.NullPointerException
- if any elements of this fluent iterable is null, or ifkeyFunction
producesnull
for any value- Since:
- 14.0
-
toArray
@GwtIncompatible("Array.newArray(Class, int)") @CheckReturnValue public final E[] toArray(java.lang.Class<E> type)
Returns an array containing all of the elements from this fluent iterable in iteration order.Stream
equivalent: if an object array is acceptable, usestream.toArray()
; iftype
is a class literal such asMyType.class
, usestream.toArray(MyType[]::new)
. Otherwise usestream.toArray( len -> (E[]) Array.newInstance(type, len))
.- Parameters:
type
- the type of the elements- Returns:
- a newly-allocated array into which all the elements of this fluent iterable have been copied
-
copyInto
public final <C extends java.util.Collection<? super E>> C copyInto(C collection)
Copies all the elements from this fluent iterable tocollection
. This is equivalent to callingIterables.addAll(collection, this)
.Stream
equivalent:stream.forEachOrdered(collection::add)
orstream.forEach(collection::add)
.- Parameters:
collection
- the collection to copy elements to- Returns:
collection
, for convenience- Since:
- 14.0
-
join
@Beta @CheckReturnValue public final java.lang.String join(Joiner joiner)
Returns aString
containing all of the elements of this fluent iterable joined withjoiner
.Stream
equivalent:joiner.join(stream.iterator())
, or, if you are not using any optionalJoiner
features,stream.collect(Collectors.joining(delimiter)
.- Since:
- 18.0
-
get
@CheckReturnValue public final E get(int position)
Returns the element at the specified position in this fluent iterable.Stream
equivalent:stream.skip(position).findFirst().get()
(but note that this throws different exception types, and throws an exception ifnull
would be returned).- Parameters:
position
- position of the element to return- Returns:
- the element at the specified position in this fluent iterable
- Throws:
java.lang.IndexOutOfBoundsException
- ifposition
is negative or greater than or equal to the size of this fluent iterable
-
-