Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * Copyright (C) 2007 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.checkArgument;
  import static com.google.common.base.Preconditions.checkNotNull;
  
  
  import java.util.Arrays;
  import java.util.HashSet;
  import java.util.List;
  import java.util.Queue;
  import java.util.Set;
  
This class contains static utility methods that operate on or return objects of type Iterable. Except as noted, each method has a corresponding java.util.Iterator-based method in the Iterators class.

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.

Author(s):
Kevin Bourrillion
Jared Levy
Since:
2.0 (imported from Google Collections Library)
  
  @GwtCompatible(emulated = true)
  public final class Iterables {
    private Iterables() {}

  
Returns an unmodifiable view of iterable.
  
    public static <T> Iterable<T> unmodifiableIterable(
        final Iterable<T> iterable) {
      checkNotNull(iterable);
      if (iterable instanceof UnmodifiableIterable ||
          iterable instanceof ImmutableCollection) {
        return iterable;
      }
      return new UnmodifiableIterable<T>(iterable);
    }

  
Simply returns its argument.

Deprecated:
no need to use this
Since:
10.0
  
    @Deprecated public static <E> Iterable<E> unmodifiableIterable(
        ImmutableCollection<E> iterable) {
      return checkNotNull(iterable);
    }
  
    private static final class UnmodifiableIterable<T> extends FluentIterable<T> {
      private final Iterable<T> iterable;
  
      private UnmodifiableIterable(Iterable<T> iterable) {
        this. = iterable;
      }
  
      @Override
      public Iterator<T> iterator() {
        return Iterators.unmodifiableIterator(.iterator());
      }
 
     @Override
     public String toString() {
       return .toString();
     }
     // no equals and hashCode; it would break the contract!
   }

  
Returns the number of elements in iterable.
 
   public static int size(Iterable<?> iterable) {
     return (iterable instanceof Collection)
         ? ((Collection<?>) iterable).size()
         : Iterators.size(iterable.iterator());
   }

  
Returns true if iterable contains any object for which equals(element) is true.
 
   public static boolean contains(Iterable<?> iterable, @Nullable Object element)
   {
     if (iterable instanceof Collection) {
       Collection<?> collection = (Collection<?>) iterable;
       try {
         return collection.contains(element);
       } catch (NullPointerException e) {
         return false;
       } catch (ClassCastException e) {
         return false;
       }
     }
     return Iterators.contains(iterable.iterator(), element);
   }

  
Removes, from an iterable, every element that belongs to the provided collection.

This method calls java.util.Collection.removeAll(java.util.Collection) if iterable is a collection, and Iterators.removeAll(java.util.Iterator,java.util.Collection) otherwise.

Parameters:
removeFrom the iterable to (potentially) remove elements from
elementsToRemove the elements to remove
Returns:
true if any element was removed from iterable
 
   public static boolean removeAll(
       Iterable<?> removeFromCollection<?> elementsToRemove) {
     return (removeFrom instanceof Collection)
         ? ((Collection<?>) removeFrom).removeAll(checkNotNull(elementsToRemove))
         : Iterators.removeAll(removeFrom.iterator(), elementsToRemove);
   }

  
Removes, from an iterable, every element that does not belong to the provided collection.

This method calls java.util.Collection.retainAll(java.util.Collection) if iterable is a collection, and Iterators.retainAll(java.util.Iterator,java.util.Collection) otherwise.

Parameters:
removeFrom the iterable to (potentially) remove elements from
elementsToRetain the elements to retain
Returns:
true if any element was removed from iterable
 
   public static boolean retainAll(
       Iterable<?> removeFromCollection<?> elementsToRetain) {
     return (removeFrom instanceof Collection)
         ? ((Collection<?>) removeFrom).retainAll(checkNotNull(elementsToRetain))
         : Iterators.retainAll(removeFrom.iterator(), elementsToRetain);
   }

  
Removes, from an iterable, every element that satisfies the provided predicate.

Parameters:
removeFrom the iterable to (potentially) remove elements from
predicate a predicate that determines whether an element should be removed
Returns:
true if any elements were removed from the iterable
Throws:
java.lang.UnsupportedOperationException if the iterable does not support remove().
Since:
2.0
 
   public static <T> boolean removeIf(
       Iterable<T> removeFromPredicate<? super T> predicate) {
     if (removeFrom instanceof RandomAccess && removeFrom instanceof List) {
       return removeIfFromRandomAccessList(
           (List<T>) removeFromcheckNotNull(predicate));
     }
     return Iterators.removeIf(removeFrom.iterator(), predicate);
   }
 
   private static <T> boolean removeIfFromRandomAccessList(
       List<T> listPredicate<? super T> predicate) {
     // Note: Not all random access lists support set() so we need to deal with
     // those that don't and attempt the slower remove() based solution.
     int from = 0;
     int to = 0;
 
     for (; from < list.size(); from++) {
       T element = list.get(from);
       if (!predicate.apply(element)) {
         if (from > to) {
           try {
             list.set(toelement);
           } catch (UnsupportedOperationException e) {
             slowRemoveIfForRemainingElements(listpredicatetofrom);
             return true;
           }
         }
         to++;
       }
     }
 
     // Clear the tail of any remaining items
     list.subList(tolist.size()).clear();
     return from != to;
   }
 
   private static <T> void slowRemoveIfForRemainingElements(List<T> list,
       Predicate<? super T> predicateint toint from) {
     // Here we know that:
     // * (to < from) and that both are valid indices.
     // * Everything with (index < to) should be kept.
     // * Everything with (to <= index < from) should be removed.
     // * The element with (index == from) should be kept.
     // * Everything with (index > from) has not been checked yet.
 
     // Check from the end of the list backwards (minimize expected cost of
     // moving elements when remove() is called). Stop before 'from' because
     // we already know that should be kept.
     for (int n = list.size() - 1; n > fromn--) {
       if (predicate.apply(list.get(n))) {
         list.remove(n);
       }
     }
     // And now remove everything in the range [to, from) (going backwards).
     for (int n = from - 1; n >= ton--) {
       list.remove(n);
     }
   }

  
Determines whether two iterables contain equal elements in the same order. More specifically, this method returns 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 boolean elementsEqual(
       Iterable<?> iterable1Iterable<?> iterable2) {
     return Iterators.elementsEqual(iterable1.iterator(), iterable2.iterator());
   }

  
Returns a string representation of iterable, with the format [e1, e2, ..., en].
 
   public static String toString(Iterable<?> iterable) {
     return Iterators.toString(iterable.iterator());
   }

  
Returns the single element contained in iterable.

Throws:
java.util.NoSuchElementException if the iterable is empty
java.lang.IllegalArgumentException if the iterable contains multiple elements
 
   public static <T> T getOnlyElement(Iterable<T> iterable) {
     return Iterators.getOnlyElement(iterable.iterator());
   }

  
Returns the single element contained in iterable, or defaultValue if the iterable is empty.

Throws:
java.lang.IllegalArgumentException if the iterator contains multiple elements
 
   public static <T> T getOnlyElement(
       Iterable<? extends T> iterable, @Nullable T defaultValue) {
     return Iterators.getOnlyElement(iterable.iterator(), defaultValue);
   }

  
Copies an iterable's elements into an array.

Parameters:
iterable the iterable to copy
type the type of the elements
Returns:
a newly-allocated array into which all the elements of the iterable have been copied
 
   @GwtIncompatible("Array.newInstance(Class, int)")
   public static <T> T[] toArray(Iterable<? extends T> iterableClass<T> type) {
     Collection<? extends T> collection = toCollection(iterable);
     T[] array = ObjectArrays.newArray(typecollection.size());
     return collection.toArray(array);
   }

  
Copies an iterable's elements into an array.

Parameters:
iterable the iterable to copy
Returns:
a newly-allocated array into which all the elements of the iterable have been copied
 
   static Object[] toArray(Iterable<?> iterable) {
     return toCollection(iterable).toArray();
   }

  
Converts an iterable into a collection. If the iterable is already a collection, it is returned. Otherwise, an java.util.ArrayList is created with the contents of the iterable in the same iteration order.
 
   private static <E> Collection<E> toCollection(Iterable<E> iterable) {
     return (iterable instanceof Collection)
         ? (Collection<E>) iterable
         : Lists.newArrayList(iterable.iterator());
   }

  
Adds all elements in iterable to collection.

Returns:
true if collection was modified as a result of this operation.
 
   public static <T> boolean addAll(
       Collection<T> addToIterable<? extends T> elementsToAdd) {
     if (elementsToAdd instanceof Collection) {
       Collection<? extends T> c = Collections2.cast(elementsToAdd);
       return addTo.addAll(c);
     }
     return Iterators.addAll(addToelementsToAdd.iterator());
   }

  
Returns the number of elements in the specified iterable that equal the specified object. This implementation avoids a full iteration when the iterable is a Multiset or java.util.Set.

 
   public static int frequency(Iterable<?> iterable, @Nullable Object element) {
     if ((iterable instanceof Multiset)) {
       return ((Multiset<?>) iterable).count(element);
     }
     if ((iterable instanceof Set)) {
       return ((Set<?>) iterable).contains(element) ? 1 : 0;
     }
     return Iterators.frequency(iterable.iterator(), element);
   }

  
Returns an iterable whose iterators cycle indefinitely over the elements of 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))

 
   public static <T> Iterable<T> cycle(final Iterable<T> iterable) {
     checkNotNull(iterable);
     return new FluentIterable<T>() {
       @Override
       public Iterator<T> iterator() {
         return Iterators.cycle(iterable);
       }
       @Override public String toString() {
         return iterable.toString() + " (cycled)";
       }
     };
   }

  
Returns an iterable whose iterators cycle indefinitely over the provided 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)))

 
   public static <T> Iterable<T> cycle(T... elements) {
     return cycle(Lists.newArrayList(elements));
   }

  
Combines two iterables into a single iterable. The returned iterable has an iterator that traverses the elements in 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.

 
   @SuppressWarnings("unchecked")
   public static <T> Iterable<T> concat(
       Iterable<? extends T> aIterable<? extends T> b) {
     checkNotNull(a);
     checkNotNull(b);
     return concat(Arrays.asList(ab));
   }

  
Combines three iterables into a single iterable. The returned iterable has an iterator that traverses the elements in 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.

 
   @SuppressWarnings("unchecked")
   public static <T> Iterable<T> concat(Iterable<? extends T> a,
       Iterable<? extends T> bIterable<? extends T> c) {
     checkNotNull(a);
     checkNotNull(b);
     checkNotNull(c);
     return concat(Arrays.asList(abc));
   }

  
Combines four iterables into a single iterable. The returned iterable has an iterator that traverses the elements in 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.

 
   @SuppressWarnings("unchecked")
   public static <T> Iterable<T> concat(Iterable<? extends T> a,
       Iterable<? extends T> bIterable<? extends T> c,
       Iterable<? extends T> d) {
     checkNotNull(a);
     checkNotNull(b);
     checkNotNull(c);
     checkNotNull(d);
     return concat(Arrays.asList(abcd));
   }

  
Combines multiple iterables into a single iterable. The returned iterable has an iterator that traverses the elements of each iterable in inputs. The input iterators are not polled until necessary.

The returned iterable's iterator supports remove() when the corresponding input iterator supports it.

Throws:
java.lang.NullPointerException if any of the provided iterables is null
 
   public static <T> Iterable<T> concat(Iterable<? extends T>... inputs) {
     return concat(ImmutableList.copyOf(inputs));
   }

  
Combines multiple iterables into a single iterable. The returned iterable has an iterator that traverses the elements of each iterable in 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.

 
   public static <T> Iterable<T> concat(
       final Iterable<? extends Iterable<? extends T>> inputs) {
     checkNotNull(inputs);
     return new FluentIterable<T>() {
       @Override
       public Iterator<T> iterator() {
         return Iterators.concat(iterators(inputs));
       }
     };
   }

  
Returns an iterator over the iterators of the given iterables.
 
   private static <T> UnmodifiableIterator<Iterator<? extends T>> iterators(
       Iterable<? extends Iterable<? extends T>> iterables) {
     final Iterator<? extends Iterable<? extends T>> iterableIterator =
         iterables.iterator();
     return new UnmodifiableIterator<Iterator<? extends T>>() {
       @Override
       public boolean hasNext() {
         return iterableIterator.hasNext();
       }
       @Override
       public Iterator<? extends T> next() {
         return iterableIterator.next().iterator();
       }
     };
   }

  
Divides an iterable into unmodifiable sublists of the given size (the final iterable may be smaller). For example, partitioning an iterable containing [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 java.util.Iterator.remove() method. The returned lists implement java.util.RandomAccess, whether or not the input list does.

Note: if iterable is a java.util.List, use Lists.partition(java.util.List,int) instead.

Parameters:
iterable the iterable to return a partitioned view of
size the desired size of each partition (the last may be smaller)
Returns:
an iterable of unmodifiable lists containing the elements of iterable divided into partitions
Throws:
java.lang.IllegalArgumentException if size is nonpositive
 
   public static <T> Iterable<List<T>> partition(
       final Iterable<T> iterablefinal int size) {
     checkNotNull(iterable);
     checkArgument(size > 0);
     return new FluentIterable<List<T>>() {
       @Override
       public Iterator<List<T>> iterator() {
         return Iterators.partition(iterable.iterator(), size);
       }
     };
   }

  
Divides an iterable into unmodifiable sublists of the given size, padding the final iterable with null values if necessary. For example, partitioning an iterable containing [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 java.util.Iterator.remove() method.

Parameters:
iterable the iterable to return a partitioned view of
size the desired size of each partition
Returns:
an iterable of unmodifiable lists containing the elements of iterable divided into partitions (the final iterable may have trailing null elements)
Throws:
java.lang.IllegalArgumentException if size is nonpositive
 
   public static <T> Iterable<List<T>> paddedPartition(
       final Iterable<T> iterablefinal int size) {
     checkNotNull(iterable);
     checkArgument(size > 0);
     return new FluentIterable<List<T>>() {
       @Override
       public Iterator<List<T>> iterator() {
         return Iterators.paddedPartition(iterable.iterator(), size);
       }
     };
   }

  
Returns the elements of unfiltered that satisfy a predicate. The resulting iterable's iterator does not support remove().
 
   public static <T> Iterable<T> filter(
       final Iterable<T> unfilteredfinal Predicate<? super T> predicate) {
     checkNotNull(unfiltered);
     checkNotNull(predicate);
     return new FluentIterable<T>() {
       @Override
       public Iterator<T> iterator() {
         return Iterators.filter(unfiltered.iterator(), predicate);
       }
     };
   }

  
Returns all instances of class type in unfiltered. The returned iterable has elements whose class is type or a subclass of type. The returned iterable's iterator does not support remove().

Parameters:
unfiltered an iterable containing objects of any type
type the type of elements desired
Returns:
an unmodifiable iterable containing all elements of the original iterable that were of the requested type
 
   @GwtIncompatible("Class.isInstance")
   public static <T> Iterable<T> filter(
       final Iterable<?> unfilteredfinal Class<T> type) {
     checkNotNull(unfiltered);
     checkNotNull(type);
     return new FluentIterable<T>() {
       @Override
       public Iterator<T> iterator() {
         return Iterators.filter(unfiltered.iterator(), type);
       }
     };
   }

  
Returns true if any element in iterable satisfies the predicate.
 
   public static <T> boolean any(
       Iterable<T> iterablePredicate<? super T> predicate) {
     return Iterators.any(iterable.iterator(), predicate);
   }

  
Returns true if every element in iterable satisfies the predicate. If iterable is empty, true is returned.
 
   public static <T> boolean all(
       Iterable<T> iterablePredicate<? super T> predicate) {
     return Iterators.all(iterable.iterator(), predicate);
   }

  
Returns the first element in 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,com.google.common.base.Predicate) or find(java.lang.Iterable,com.google.common.base.Predicate,java.lang.Object) instead.

Throws:
java.util.NoSuchElementException if no element in iterable matches the given predicate
 
   public static <T> T find(Iterable<T> iterable,
       Predicate<? super T> predicate) {
     return Iterators.find(iterable.iterator(), predicate);
   }

  
Returns the first element in 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).

Since:
7.0
 
   public static <T> T find(Iterable<? extends T> iterable,
       Predicate<? super T> predicate, @Nullable T defaultValue) {
     return Iterators.find(iterable.iterator(), predicatedefaultValue);
   }

  
Returns an com.google.common.base.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.

Since:
11.0
 
   public static <T> Optional<T> tryFind(Iterable<T> iterable,
       Predicate<? super T> predicate) {
     return Iterators.tryFind(iterable.iterator(), predicate);
   }

  
Returns the index in 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.

Since:
2.0
 
   public static <T> int indexOf(
       Iterable<T> iterablePredicate<? super T> predicate) {
     return Iterators.indexOf(iterable.iterator(), predicate);
   }

  
Returns an iterable that applies function to each element of fromIterable.

The returned iterable's iterator supports remove() if the provided 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,com.google.common.base.Function) and Collections2.transform(java.util.Collection,com.google.common.base.Function).

 
   public static <F, T> Iterable<T> transform(final Iterable<F> fromIterable,
       final Function<? super F, ? extends T> function) {
     checkNotNull(fromIterable);
     checkNotNull(function);
     return new FluentIterable<T>() {
       @Override
       public Iterator<T> iterator() {
         return Iterators.transform(fromIterable.iterator(), function);
       }
     };
   }

  
Returns the element at the specified position in an iterable.

Parameters:
position position of the element to return
Returns:
the element at the specified position in iterable
Throws:
java.lang.IndexOutOfBoundsException if position is negative or greater than or equal to the size of iterable
 
   public static <T> T get(Iterable<T> iterableint position) {
     checkNotNull(iterable);
     if (iterable instanceof List) {
       return ((List<T>) iterable).get(position);
     }
 
     if (iterable instanceof Collection) {
       // Can check both ends
       Collection<T> collection = (Collection<T>) iterable;
       Preconditions.checkElementIndex(positioncollection.size());
     } else {
       // Can only check the lower end
       checkNonnegativeIndex(position);
     }
     return Iterators.get(iterable.iterator(), position);
   }
 
   private static void checkNonnegativeIndex(int position) {
     if (position < 0) {
       throw new IndexOutOfBoundsException(
           "position cannot be negative: " + position);
     }
   }

  
Returns the element at the specified position in an iterable or a default value otherwise.

Parameters:
position position of the element to return
defaultValue the default value to return if position is greater than or equal to the size of the iterable
Returns:
the element at the specified position in iterable or defaultValue if iterable contains fewer than position + 1 elements.
Throws:
java.lang.IndexOutOfBoundsException if position is negative
Since:
4.0
 
   public static <T> T get(Iterable<? extends T> iterableint position, @Nullable T defaultValue) {
     checkNotNull(iterable);
     checkNonnegativeIndex(position);
 
     try {
       return get(iterableposition);
     } catch (IndexOutOfBoundsException e) {
       return defaultValue;
     }
   }

  
Returns the first element in iterable or defaultValue if the iterable is empty. The Iterators analog to this method is Iterators.getNext(java.util.Iterator,java.lang.Object).

Parameters:
defaultValue the default value to return if the iterable is empty
Returns:
the first element of iterable or the default value
Since:
7.0
 
   public static <T> T getFirst(Iterable<? extends T> iterable, @Nullable T defaultValue) {
     return Iterators.getNext(iterable.iterator(), defaultValue);
   }

  
Returns the last element of iterable.

Returns:
the last element of iterable
Throws:
java.util.NoSuchElementException if the iterable is empty
 
   public static <T> T getLast(Iterable<T> iterable) {
     // TODO(kevinb): Support a concurrently modified collection?
     if (iterable instanceof List) {
       List<T> list = (List<T>) iterable;
       if (list.isEmpty()) {
         throw new NoSuchElementException();
       }
       return getLastInNonemptyList(list);
     }
 
     /*
      * 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 (iterable instanceof SortedSet) {
       SortedSet<T> sortedSet = (SortedSet<T>) iterable;
       return sortedSet.last();
     }
 
     return Iterators.getLast(iterable.iterator());
   }

  
Returns the last element of iterable or defaultValue if the iterable is empty.

Parameters:
defaultValue the value to return if iterable is empty
Returns:
the last element of iterable or the default value
Since:
3.0
 
   public static <T> T getLast(Iterable<? extends T> iterable, @Nullable T defaultValue) {
     if (iterable instanceof Collection) {
       Collection<? extends T> collection = Collections2.cast(iterable);
       if (collection.isEmpty()) {
         return defaultValue;
       }
     }
 
     if (iterable instanceof List) {
       List<? extends T> list = Lists.cast(iterable);
       return getLastInNonemptyList(list);
     }
 
     /*
      * 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 (iterable instanceof SortedSet) {
       SortedSet<? extends T> sortedSet = Sets.cast(iterable);
       return sortedSet.last();
     }
 
     return Iterators.getLast(iterable.iterator(), defaultValue);
   }
 
   private static <T> T getLastInNonemptyList(List<T> list) {
     return list.get(list.size() - 1);
   }

  
Returns a view of 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 java.lang.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 java.lang.IllegalStateException.

Since:
3.0
 
   public static <T> Iterable<T> skip(final Iterable<T> iterable,
       final int numberToSkip) {
     checkNotNull(iterable);
     checkArgument(numberToSkip >= 0, "number to skip cannot be negative");
 
     if (iterable instanceof List) {
       final List<T> list = (List<T>) iterable;
       return new FluentIterable<T>() {
         @Override
         public Iterator<T> iterator() {
           // TODO(kevinb): Support a concurrently modified collection?
           return (numberToSkip >= list.size())
               ? Iterators.<T>emptyIterator()
               : list.subList(numberToSkiplist.size()).iterator();
         }
       };
     }
 
     return new FluentIterable<T>() {
       @Override
       public Iterator<T> iterator() {
         final Iterator<T> iterator = iterable.iterator();
 
         Iterators.skip(iteratornumberToSkip);
 
         /*
          * We can't just return the iterator because an immediate call to its
          * remove() method would remove one of the skipped elements instead of
          * throwing an IllegalStateException.
          */
         return new Iterator<T>() {
           boolean atStart = true;
 
           @Override
           public boolean hasNext() {
             return iterator.hasNext();
           }
 
           @Override
           public T next() {
             if (!hasNext()) {
               throw new NoSuchElementException();
             }
 
             try {
               return iterator.next();
             } finally {
                = false;
             }
           }
 
           @Override
           public void remove() {
             if () {
               throw new IllegalStateException();
             }
             iterator.remove();
           }
         };
       }
     };
   }

  
Creates an iterable with the first limitSize elements of the given iterable. If the original iterable does not contain that many elements, the returned iterator will have the same behavior as the original iterable. The returned iterable's iterator supports remove() if the original iterator does.

Parameters:
iterable the iterable to limit
limitSize the maximum number of elements in the returned iterator
Throws:
java.lang.IllegalArgumentException if limitSize is negative
Since:
3.0
 
   public static <T> Iterable<T> limit(
       final Iterable<T> iterablefinal int limitSize) {
     checkNotNull(iterable);
     checkArgument(limitSize >= 0, "limit is negative");
     return new FluentIterable<T>() {
       @Override
       public Iterator<T> iterator() {
         return Iterators.limit(iterable.iterator(), limitSize);
       }
     };
   }

  
Returns a view of the supplied iterable that wraps each generated java.util.Iterator through Iterators.consumingIterator(java.util.Iterator).

Note: If iterable is a java.util.Queue, the returned iterable will get entries from java.util.Queue.remove() since java.util.Queue's iteration order is undefined. Calling java.util.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 java.util.Iterator.next().

Parameters:
iterable the iterable to wrap
Returns:
a view of the supplied iterable that wraps each generated iterator through Iterators.consumingIterator(java.util.Iterator); for queues, an iterable that generates iterators that return and consume the queue's elements in queue order
Since:
2.0
See also:
Iterators.consumingIterator(java.util.Iterator)
 
   public static <T> Iterable<T> consumingIterable(final Iterable<T> iterable) {
     if (iterable instanceof Queue) {
       return new FluentIterable<T>() {
         @Override
         public Iterator<T> iterator() {
           return new ConsumingQueueIterator<T>((Queue<T>) iterable);
         }
       };
     }
 
     checkNotNull(iterable);
 
     return new FluentIterable<T>() {
       @Override
       public Iterator<T> iterator() {
         return Iterators.consumingIterator(iterable.iterator());
       }
     };
   }
 
   private static class ConsumingQueueIterator<T> extends AbstractIterator<T> {
    private final Queue<T> queue;
    private ConsumingQueueIterator(Queue<T> queue) {
      this. = queue;
    }
    @Override public T computeNext() {
      try {
        return .remove();
      } catch (NoSuchElementException e) {
        return endOfData();
      }
    }
  }
  // Methods only in Iterables, not in Iterators

  
Adapts a list to an iterable with reversed iteration order. It is especially useful in foreach-style loops:
   List<String> mylist = ...
   for (String str : Iterables.reverse(mylist)) {
     ...
   }
There is no corresponding method in Iterators, since java.lang.Iterable.iterator() can simply be invoked on the result of calling this method.

Deprecated:
use Lists.reverse(java.util.List) or ImmutableList.reverse(). This method is scheduled for deletion in July 2012.
Returns:
an iterable with the same elements as the list, in reverse
  public static <T> Iterable<T> reverse(final List<T> list) {
    return Lists.reverse(list);
  }

  
Determines if the given iterable contains no elements.

There is no precise java.util.Iterator equivalent to this method, since one can only ask an iterator whether it has any elements remaining (which one does using java.util.Iterator.hasNext()).

Returns:
true if the iterable contains no elements
  public static boolean isEmpty(Iterable<?> iterable) {
    if (iterable instanceof Collection) {
      return ((Collection<?>) iterable).isEmpty();
    }
    return !iterable.iterator().hasNext();
  }
  // Non-public

  
Removes the specified element from the specified iterable.

This method iterates over the iterable, checking each element returned by the iterator in turn to see if it equals the object o. If they are equal, it is removed from the iterable with the iterator's remove method. At most one element is removed, even if the iterable contains multiple members that equal o.

Warning: Do not use this method for a collection, such as a java.util.HashSet, that has a fast remove method.

Parameters:
iterable the iterable from which to remove
o an element to remove from the collection
Returns:
true if the iterable changed as a result
Throws:
java.lang.UnsupportedOperationException if the iterator does not support the remove method and the iterable contains the object
  static boolean remove(Iterable<?> iterable, @Nullable Object o) {
    Iterator<?> i = iterable.iterator();
    while (i.hasNext()) {
      if (Objects.equal(i.next(), o)) {
        i.remove();
        return true;
      }
    }
    return false;
  }

  
Returns an iterable over the merged contents of all given 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.

Since:
11.0
  public static <T> Iterable<T> mergeSorted(
      final Iterable<? extends Iterable<? extends T>> iterables,
      final Comparator<? super T> comparator) {
    checkNotNull(iterables"iterables");
    checkNotNull(comparator"comparator");
    Iterable<T> iterable = new FluentIterable<T>() {
      @Override
      public Iterator<T> iterator() {
        return Iterators.mergeSorted(
            Iterables.transform(iterables, Iterables.<T>toIterator()),
            comparator);
      }
    };
    return new UnmodifiableIterable<T>(iterable);
  }
  // TODO(user): Is this the best place for this? Move to fluent functions?
  // Useful as a public method?
  private static <T> Function<Iterable<? extends T>, Iterator<? extends T>>
      toIterator() {
    return new Function<Iterable<? extends T>, Iterator<? extends T>>() {
      @Override
      public Iterator<? extends T> apply(Iterable<? extends T> iterable) {
        return iterable.iterator();
      }
    };
  }
New to GrepCode? Check out our FAQ X