Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2008 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.collect;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 
 
 import java.util.List;
 
 import  javax.annotation.Nullable;

FluentIterable provides a rich interface for manipulating Iterable instances in a chained fashion. A FluentIterable can be created from an Iterable, or from a set of elements. The following types of methods are provided on FluentIterable:
  • chained methods which return a new FluentIterable based in some way on the contents of the current one (for example transform)
  • conversion methods which copy the FluentIterable's contents into a new collection or array (for example toList)
  • element extraction methods which facilitate the retrieval of certain elements (for example last)
  • query methods which answer questions about the FluentIterable's contents (for example anyMatch)

Here is an example that merges the lists returned by two separate database calls, transforms it by invoking toString() on each element, and returns the first 10 elements as an ImmutableList:

   FluentIterable
       .from(database.getClientList())
       .filter(activeInLastMonth())
       .transform(Functions.toStringFunction())
       .limit(10)
       .toList();
Anything which can be done using FluentIterable could be done in a different fashion (often with Iterables), however the use of FluentIterable makes many sets of operations significantly more concise.

Author(s):
Marcin Mikosik
Since:
12.0
 
 @GwtCompatible(emulated = true)
 public abstract class FluentIterable<E> implements Iterable<E> {
   // We store 'iterable' and use it instead of 'this' to allow Iterables to perform instanceof
   // checks on the _original_ iterable when FluentIterable.from is used.
   private final Iterable<E> iterable;

  
Constructor for use by subclasses.
 
   protected FluentIterable() {
     this. = this;
   }
 
   FluentIterable(Iterable<E> iterable) {
     this. = checkNotNull(iterable);
   }

  
Returns a fluent iterable that wraps iterable, or iterable itself if it is already a FluentIterable.
 
   public static <E> FluentIterable<E> from(final Iterable<E> iterable) {
     return (iterable instanceof FluentIterable) ? (FluentIterable<E>) iterable
         : new FluentIterable<E>(iterable) {
           @Override
           public Iterator<E> iterator() {
             return iterable.iterator();
           }
         };
   }

  
Construct a fluent iterable from another fluent iterable. This is obviously never necessary, but is intended to help call out cases where one migration from Iterable to FluentIterable has obviated the need to explicitly convert to a FluentIterable.

Deprecated:
instances of FluentIterable don't need to be converted to FluentIterable
  public static <E> FluentIterable<E> from(FluentIterable<E> iterable) {
    return checkNotNull(iterable);
  }

  
Returns a string representation of this fluent iterable, with the format [e1, e2, ..., en].
  public String toString() {
    return Iterables.toString();
  }

  
Returns the number of elements in this fluent iterable.
  public final int size() {
    return Iterables.size();
  }

  
Returns true if this fluent iterable contains any object for which equals(element) is true.
  public final boolean contains(@Nullable Object element) {
    return Iterables.contains(element);
  }

  
Returns a fluent iterable whose Iterator cycles indefinitely over the elements of this fluent iterable.

That iterator supports remove() if iterable.iterator() does. After remove() is called, subsequent cycles omit the removed element, which is no longer in this fluent iterable. The iterator's hasNext() method returns true 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.

  public final FluentIterable<E> cycle() {
    return from(Iterables.cycle());
  }

  
Returns the elements from this fluent iterable that satisfy a predicate. The resulting fluent iterable's iterator does not support remove().
  public final FluentIterable<E> filter(Predicate<? super E> predicate) {
    return from(Iterables.filter(predicate));
  }

  
Returns the elements from this fluent iterable that are instances of class type.

Parameters:
type the type of elements desired
  @GwtIncompatible("Class.isInstance")
  public final <T> FluentIterable<T> filter(Class<T> type) {
    return from(Iterables.filter(type));
  }

  
Returns true if any element in this fluent iterable satisfies the predicate.
  public final boolean anyMatch(Predicate<? super E> predicate) {
    return Iterables.any(predicate);
  }

  
Returns true if every element in this fluent iterable satisfies the predicate. If this fluent iterable is empty, true is returned.
  public final boolean allMatch(Predicate<? super E> predicate) {
    return Iterables.all(predicate);
  }

  
Returns an Optional containing the first element in this fluent iterable that satisfies the given predicate, if such an element exists.

Warning: avoid using a predicate that matches null. If null is matched in this fluent iterable, a NullPointerException will be thrown.

  public final Optional<E> firstMatch(Predicate<? super E> predicate) {
    return Iterables.tryFind(predicate);
  }

  
Returns a fluent iterable that applies function to each element of this fluent iterable.

The returned fluent iterable's iterator supports remove() if this iterable's iterator does. After a successful remove() call, this fluent iterable no longer contains the corresponding element.

  public final <T> FluentIterable<T> transform(Function<? super E, T> function) {
    return from(Iterables.transform(function));
  }

  
Applies function 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 successful remove() call, the returned fluent iterable no longer contains the corresponding element.

Since:
13.0 (required Function<E, Iterable<T>> until 14.0)
      Function<? super E, ? extends Iterable<? extends T>> function) {
    return from(Iterables.concat(transform(function)));
  }

  
Returns an Optional containing the first element in this fluent iterable. If the iterable is empty, Optional.absent() is returned.

Throws:
NullPointerException if the first element is null; if this is a possibility, use iterator().next() or Iterables.getFirst instead.
  public final Optional<E> first() {
    Iterator<E> iterator = .iterator();
    return iterator.hasNext()
        ? Optional.of(iterator.next())
        : Optional.<E>absent();
  }

  
Returns an Optional containing the last element in this fluent iterable. If the iterable is empty, Optional.absent() is returned.

Throws:
NullPointerException if the last element is null; if this is a possibility, use Iterables.getLast instead.
  public final Optional<E> last() {
    // Iterables#getLast was inlined here so we don't have to throw/catch a NSEE
    // TODO(kevinb): Support a concurrently modified collection?
    if ( instanceof List) {
      List<E> list = (List<E>) ;
      if (list.isEmpty()) {
        return Optional.absent();
      }
      return Optional.of(list.get(list.size() - 1));
    }
    Iterator<E> iterator = .iterator();
    if (!iterator.hasNext()) {
      return Optional.absent();
    }
    /*
     * TODO(kevinb): consider whether this "optimization" is worthwhile. Users
     * with SortedSets tend to know they are SortedSets and probably would not
     * call this method.
     */
    if ( instanceof SortedSet) {
      SortedSet<E> sortedSet = (SortedSet<E>) ;
      return Optional.of(sortedSet.last());
    }
    while (true) {
      E current = iterator.next();
      if (!iterator.hasNext()) {
        return Optional.of(current);
      }
    }
  }

  
Returns a view of this fluent iterable that skips its first numberToSkip elements. If this fluent iterable contains fewer than numberToSkip 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 first numberToSkip elements that exist when the iterator is created, not when skip() is called.

The returned fluent iterable's iterator supports remove() if the Iterator of this fluent iterable supports it. Note that it is not possible to delete the last skipped element by immediately calling remove() on the returned fluent iterable's iterator, as the Iterator contract states that a call to * remove() before a call to next() will throw an IllegalStateException.

  public final FluentIterable<E> skip(int numberToSkip) {
    return from(Iterables.skip(numberToSkip));
  }

  
Creates a fluent iterable with the first size 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 supports remove() if this fluent iterable's iterator does.

Parameters:
size the maximum number of elements in the returned fluent iterable
Throws:
IllegalArgumentException if size is negative
  public final FluentIterable<E> limit(int size) {
    return from(Iterables.limit(size));
  }

  
Determines whether this fluent iterable is empty.
  public final boolean isEmpty() {
    return !.iterator().hasNext();
  }

  
Returns an ImmutableList containing all of the elements from this fluent iterable in proper sequence.

Since:
14.0 (since 12.0 as toImmutableList()).
  public final ImmutableList<E> toList() {
    return ImmutableList.copyOf();
  }

  
Returns an ImmutableList containing all of the elements from this FluentIterable in the order specified by comparator. To produce an ImmutableList sorted by its natural ordering, use toSortedList(Ordering.natural()).

Parameters:
comparator the function by which to sort list elements
Throws:
NullPointerException if any element is null
Since:
14.0 (since 13.0 as toSortedImmutableList()).
  @Beta
  public final ImmutableList<E> toSortedList(Comparator<? super E> comparator) {
    return Ordering.from(comparator).immutableSortedCopy();
  }

  
Returns an ImmutableSet containing all of the elements from this fluent iterable with duplicates removed.

Since:
14.0 (since 12.0 as toImmutableSet()).
  public final ImmutableSet<E> toSet() {
    return ImmutableSet.copyOf();
  }

  
Returns an ImmutableSortedSet containing all of the elements from this FluentIterable in the order specified by comparator, with duplicates (determined by comparator.compare(x, y) == 0) removed. To produce an ImmutableSortedSet sorted by its natural ordering, use toSortedSet(Ordering.natural()).

Parameters:
comparator the function by which to sort set elements
Throws:
NullPointerException if any element is null
Since:
14.0 (since 12.0 as toImmutableSortedSet()).
  public final ImmutableSortedSet<E> toSortedSet(Comparator<? super E> comparator) {
    return ImmutableSortedSet.copyOf(comparator);
  }

  
Returns an immutable map for which the elements of this FluentIterable are the keys in the same order, mapped to values by the given function. If this iterable contains duplicate elements, the returned map will contain each distinct element once in the order it first appears.

Throws:
NullPointerException if any element of this iterable is null, or if valueFunction produces null for any key
Since:
14.0
  public final <V> ImmutableMap<E, V> toMap(Function<? super E, V> valueFunction) {
    return Maps.toMap(valueFunction);
  }

  
Creates an index ImmutableListMultimap that contains the results of applying a specified function to each item in this FluentIterable 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:
NullPointerException if any of the following cases is true:
  • keyFunction is null
  • An element in this fluent iterable is null
  • keyFunction returns null for any element of this iterable
Since:
14.0
  public final <K> ImmutableListMultimap<K, E> index(Function<? super E, K> keyFunction) {
    return Multimaps.index(keyFunction);
  }

  
Returns an immutable map for which the java.util.Map.values are the elements of this FluentIterable in the given order, and each key is the product of invoking a supplied function on its corresponding value.

Parameters:
keyFunction the function used to produce the key for each value
Throws:
IllegalArgumentException if keyFunction produces the same key for more than one value in this fluent iterable
NullPointerException if any element of this fluent iterable is null, or if keyFunction produces null for any value
Since:
14.0
  public final <K> ImmutableMap<K, E> uniqueIndex(Function<? super E, K> keyFunction) {
    return Maps.uniqueIndex(keyFunction);
  }

  
Returns an ImmutableList containing all of the elements from this fluent iterable in proper sequence.

Deprecated:
Use toList() instead. This method is scheduled for removal in Guava 15.0.
  public final ImmutableList<E> toImmutableList() {
    return toList();
  }

  
Returns an ImmutableList containing all of the elements from this FluentIterable in the order specified by comparator. To produce an ImmutableList sorted by its natural ordering, use toSortedImmutableList(Ordering.natural()).

Deprecated:
Use toSortedList(Comparator) instead. This method is scheduled for removal in Guava 15.0.
Parameters:
comparator the function by which to sort list elements
Throws:
NullPointerException if any element is null
Since:
13.0
  public final ImmutableList<E> toSortedImmutableList(Comparator<? super E> comparator) {
    return toSortedList(comparator);
  }

  
Returns an ImmutableSet containing all of the elements from this fluent iterable with duplicates removed.

Deprecated:
Use toSet() instead. This method is scheduled for removal in Guava 15.0.
  public final ImmutableSet<E> toImmutableSet() {
    return toSet();
  }

  
Returns an ImmutableSortedSet containing all of the elements from this FluentIterable in the order specified by comparator, with duplicates (determined by comparator.compare(x, y) == 0) removed. To produce an ImmutableSortedSet sorted by its natural ordering, use toImmutableSortedSet(Ordering.natural()).

Deprecated:
Use toSortedSet(Comparator) instead. This method is scheduled for removal in Guava 15.0.
Parameters:
comparator the function by which to sort set elements
Throws:
NullPointerException if any element is null
  public final ImmutableSortedSet<E> toImmutableSortedSet(Comparator<? super E> comparator) {
    return toSortedSet(comparator);
  }

  
Returns an array containing all of the elements from this fluent iterable in iteration order.

Parameters:
type the type of the elements
Returns:
a newly-allocated array into which all the elements of this fluent iterable have been copied
  @GwtIncompatible("Array.newArray(Class, int)")
  public final E[] toArray(Class<E> type) {
    return Iterables.toArray(type);
  }

  
Copies all the elements from this fluent iterable to collection. This is equivalent to calling Iterables.addAll(collection, this).

Parameters:
collection the collection to copy elements to
Returns:
collection, for convenience
Since:
14.0
  public final <C extends Collection<? super E>> C copyInto(C collection) {
    checkNotNull(collection);
    if ( instanceof Collection) {
      collection.addAll(Collections2.cast());
    } else {
      for (E item : ) {
        collection.add(item);
      }
    }
    return collection;
  }

  
Returns the element at the specified position in this fluent iterable.

Parameters:
position position of the element to return
Returns:
the element at the specified position in this fluent iterable
Throws:
IndexOutOfBoundsException if position is negative or greater than or equal to the size of this fluent iterable
  public final E get(int position) {
    return Iterables.get(position);
  }

  
Function that transforms Iterable<E> into a fluent iterable.
  private static class FromIterableFunction<E>
      implements Function<Iterable<E>, FluentIterable<E>> {
    @Override
    public FluentIterable<E> apply(Iterable<E> fromObject) {
      return FluentIterable.from(fromObject);
    }
  }
New to GrepCode? Check out our FAQ X