001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkArgument;
020import static com.google.common.base.Preconditions.checkNotNull;
021import static com.google.common.collect.CollectPreconditions.checkRemove;
022
023import com.google.common.annotations.Beta;
024import com.google.common.annotations.GwtCompatible;
025import com.google.common.annotations.GwtIncompatible;
026import com.google.common.base.Function;
027import com.google.common.base.Optional;
028import com.google.common.base.Predicate;
029
030import java.util.Collection;
031import java.util.Collections;
032import java.util.Comparator;
033import java.util.Iterator;
034import java.util.List;
035import java.util.NoSuchElementException;
036import java.util.Queue;
037import java.util.RandomAccess;
038import java.util.Set;
039
040import javax.annotation.CheckReturnValue;
041import javax.annotation.Nullable;
042
043/**
044 * This class contains static utility methods that operate on or return objects
045 * of type {@code Iterable}. Except as noted, each method has a corresponding
046 * {@link Iterator}-based method in the {@link Iterators} class.
047 *
048 * <p><i>Performance notes:</i> Unless otherwise noted, all of the iterables
049 * produced in this class are <i>lazy</i>, which means that their iterators
050 * only advance the backing iteration when absolutely necessary.
051 *
052 * <p>See the Guava User Guide article on <a href=
053 * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#iterables">
054 * {@code Iterables}</a>.
055 *
056 * @author Kevin Bourrillion
057 * @author Jared Levy
058 * @since 2.0
059 */
060@GwtCompatible(emulated = true)
061public final class Iterables {
062  private Iterables() {}
063
064  /** Returns an unmodifiable view of {@code iterable}. */
065  public static <T> Iterable<T> unmodifiableIterable(final Iterable<T> iterable) {
066    checkNotNull(iterable);
067    if (iterable instanceof UnmodifiableIterable || iterable instanceof ImmutableCollection) {
068      return iterable;
069    }
070    return new UnmodifiableIterable<T>(iterable);
071  }
072
073  /**
074   * Simply returns its argument.
075   *
076   * @deprecated no need to use this
077   * @since 10.0
078   */
079  @Deprecated
080  public static <E> Iterable<E> unmodifiableIterable(ImmutableCollection<E> iterable) {
081    return checkNotNull(iterable);
082  }
083
084  private static final class UnmodifiableIterable<T> extends FluentIterable<T> {
085    private final Iterable<T> iterable;
086
087    private UnmodifiableIterable(Iterable<T> iterable) {
088      this.iterable = iterable;
089    }
090
091    @Override
092    public Iterator<T> iterator() {
093      return Iterators.unmodifiableIterator(iterable.iterator());
094    }
095
096    @Override
097    public String toString() {
098      return iterable.toString();
099    }
100    // no equals and hashCode; it would break the contract!
101  }
102
103  /**
104   * Returns the number of elements in {@code iterable}.
105   */
106  public static int size(Iterable<?> iterable) {
107    return (iterable instanceof Collection)
108        ? ((Collection<?>) iterable).size()
109        : Iterators.size(iterable.iterator());
110  }
111
112  /**
113   * Returns {@code true} if {@code iterable} contains any object for which {@code equals(element)}
114   * is true.
115   */
116  public static boolean contains(Iterable<?> iterable, @Nullable Object element) {
117    if (iterable instanceof Collection) {
118      Collection<?> collection = (Collection<?>) iterable;
119      return Collections2.safeContains(collection, element);
120    }
121    return Iterators.contains(iterable.iterator(), element);
122  }
123
124  /**
125   * Removes, from an iterable, every element that belongs to the provided
126   * collection.
127   *
128   * <p>This method calls {@link Collection#removeAll} if {@code iterable} is a
129   * collection, and {@link Iterators#removeAll} otherwise.
130   *
131   * @param removeFrom the iterable to (potentially) remove elements from
132   * @param elementsToRemove the elements to remove
133   * @return {@code true} if any element was removed from {@code iterable}
134   */
135  public static boolean removeAll(Iterable<?> removeFrom, Collection<?> elementsToRemove) {
136    return (removeFrom instanceof Collection)
137        ? ((Collection<?>) removeFrom).removeAll(checkNotNull(elementsToRemove))
138        : Iterators.removeAll(removeFrom.iterator(), elementsToRemove);
139  }
140
141  /**
142   * Removes, from an iterable, every element that does not belong to the
143   * provided collection.
144   *
145   * <p>This method calls {@link Collection#retainAll} if {@code iterable} is a
146   * collection, and {@link Iterators#retainAll} otherwise.
147   *
148   * @param removeFrom the iterable to (potentially) remove elements from
149   * @param elementsToRetain the elements to retain
150   * @return {@code true} if any element was removed from {@code iterable}
151   */
152  public static boolean retainAll(Iterable<?> removeFrom, Collection<?> elementsToRetain) {
153    return (removeFrom instanceof Collection)
154        ? ((Collection<?>) removeFrom).retainAll(checkNotNull(elementsToRetain))
155        : Iterators.retainAll(removeFrom.iterator(), elementsToRetain);
156  }
157
158  /**
159   * Removes, from an iterable, every element that satisfies the provided
160   * predicate.
161   *
162   * @param removeFrom the iterable to (potentially) remove elements from
163   * @param predicate a predicate that determines whether an element should
164   *     be removed
165   * @return {@code true} if any elements were removed from the iterable
166   *
167   * @throws UnsupportedOperationException if the iterable does not support
168   *     {@code remove()}.
169   * @since 2.0
170   */
171  public static <T> boolean removeIf(Iterable<T> removeFrom, Predicate<? super T> predicate) {
172    if (removeFrom instanceof RandomAccess && removeFrom instanceof List) {
173      return removeIfFromRandomAccessList((List<T>) removeFrom, checkNotNull(predicate));
174    }
175    return Iterators.removeIf(removeFrom.iterator(), predicate);
176  }
177
178  private static <T> boolean removeIfFromRandomAccessList(
179      List<T> list, Predicate<? super T> predicate) {
180    // Note: Not all random access lists support set() so we need to deal with
181    // those that don't and attempt the slower remove() based solution.
182    int from = 0;
183    int to = 0;
184
185    for (; from < list.size(); from++) {
186      T element = list.get(from);
187      if (!predicate.apply(element)) {
188        if (from > to) {
189          try {
190            list.set(to, element);
191          } catch (UnsupportedOperationException e) {
192            slowRemoveIfForRemainingElements(list, predicate, to, from);
193            return true;
194          }
195        }
196        to++;
197      }
198    }
199
200    // Clear the tail of any remaining items
201    list.subList(to, list.size()).clear();
202    return from != to;
203  }
204
205  private static <T> void slowRemoveIfForRemainingElements(
206      List<T> list, Predicate<? super T> predicate, int to, int from) {
207    // Here we know that:
208    // * (to < from) and that both are valid indices.
209    // * Everything with (index < to) should be kept.
210    // * Everything with (to <= index < from) should be removed.
211    // * The element with (index == from) should be kept.
212    // * Everything with (index > from) has not been checked yet.
213
214    // Check from the end of the list backwards (minimize expected cost of
215    // moving elements when remove() is called). Stop before 'from' because
216    // we already know that should be kept.
217    for (int n = list.size() - 1; n > from; n--) {
218      if (predicate.apply(list.get(n))) {
219        list.remove(n);
220      }
221    }
222    // And now remove everything in the range [to, from) (going backwards).
223    for (int n = from - 1; n >= to; n--) {
224      list.remove(n);
225    }
226  }
227
228  /**
229   * Removes and returns the first matching element, or returns {@code null} if there is none.
230   */
231  @Nullable
232  static <T> T removeFirstMatching(Iterable<T> removeFrom, Predicate<? super T> predicate) {
233    checkNotNull(predicate);
234    Iterator<T> iterator = removeFrom.iterator();
235    while (iterator.hasNext()) {
236      T next = iterator.next();
237      if (predicate.apply(next)) {
238        iterator.remove();
239        return next;
240      }
241    }
242    return null;
243  }
244
245  /**
246   * Determines whether two iterables contain equal elements in the same order.
247   * More specifically, this method returns {@code true} if {@code iterable1}
248   * and {@code iterable2} contain the same number of elements and every element
249   * of {@code iterable1} is equal to the corresponding element of
250   * {@code iterable2}.
251   */
252  @CheckReturnValue
253  public static boolean elementsEqual(Iterable<?> iterable1, Iterable<?> iterable2) {
254    if (iterable1 instanceof Collection && iterable2 instanceof Collection) {
255      Collection<?> collection1 = (Collection<?>) iterable1;
256      Collection<?> collection2 = (Collection<?>) iterable2;
257      if (collection1.size() != collection2.size()) {
258        return false;
259      }
260    }
261    return Iterators.elementsEqual(iterable1.iterator(), iterable2.iterator());
262  }
263
264  /**
265   * Returns a string representation of {@code iterable}, with the format {@code
266   * [e1, e2, ..., en]} (that is, identical to {@link java.util.Arrays
267   * Arrays}{@code .toString(Iterables.toArray(iterable))}). Note that for
268   * <i>most</i> implementations of {@link Collection}, {@code
269   * collection.toString()} also gives the same result, but that behavior is not
270   * generally guaranteed.
271   */
272  public static String toString(Iterable<?> iterable) {
273    return Iterators.toString(iterable.iterator());
274  }
275
276  /**
277   * Returns the single element contained in {@code iterable}.
278   *
279   * @throws NoSuchElementException if the iterable is empty
280   * @throws IllegalArgumentException if the iterable contains multiple
281   *     elements
282   */
283  public static <T> T getOnlyElement(Iterable<T> iterable) {
284    return Iterators.getOnlyElement(iterable.iterator());
285  }
286
287  /**
288   * Returns the single element contained in {@code iterable}, or {@code
289   * defaultValue} if the iterable is empty.
290   *
291   * @throws IllegalArgumentException if the iterator contains multiple
292   *     elements
293   */
294  @Nullable
295  public static <T> T getOnlyElement(Iterable<? extends T> iterable, @Nullable T defaultValue) {
296    return Iterators.getOnlyElement(iterable.iterator(), defaultValue);
297  }
298
299  /**
300   * Copies an iterable's elements into an array.
301   *
302   * @param iterable the iterable to copy
303   * @param type the type of the elements
304   * @return a newly-allocated array into which all the elements of the iterable
305   *     have been copied
306   */
307  @GwtIncompatible("Array.newInstance(Class, int)")
308  public static <T> T[] toArray(Iterable<? extends T> iterable, Class<T> type) {
309    Collection<? extends T> collection = toCollection(iterable);
310    T[] array = ObjectArrays.newArray(type, collection.size());
311    return collection.toArray(array);
312  }
313
314  static <T> T[] toArray(Iterable<? extends T> iterable, T[] array) {
315    Collection<? extends T> collection = toCollection(iterable);
316    return collection.toArray(array);
317  }
318
319  /**
320   * Copies an iterable's elements into an array.
321   *
322   * @param iterable the iterable to copy
323   * @return a newly-allocated array into which all the elements of the iterable
324   *     have been copied
325   */
326  static Object[] toArray(Iterable<?> iterable) {
327    return toCollection(iterable).toArray();
328  }
329
330  /**
331   * Converts an iterable into a collection. If the iterable is already a
332   * collection, it is returned. Otherwise, an {@link java.util.ArrayList} is
333   * created with the contents of the iterable in the same iteration order.
334   */
335  private static <E> Collection<E> toCollection(Iterable<E> iterable) {
336    return (iterable instanceof Collection)
337        ? (Collection<E>) iterable
338        : Lists.newArrayList(iterable.iterator());
339  }
340
341  /**
342   * Adds all elements in {@code iterable} to {@code collection}.
343   *
344   * @return {@code true} if {@code collection} was modified as a result of this
345   *     operation.
346   */
347  public static <T> boolean addAll(Collection<T> addTo, Iterable<? extends T> elementsToAdd) {
348    if (elementsToAdd instanceof Collection) {
349      Collection<? extends T> c = Collections2.cast(elementsToAdd);
350      return addTo.addAll(c);
351    }
352    return Iterators.addAll(addTo, checkNotNull(elementsToAdd).iterator());
353  }
354
355  /**
356   * Returns the number of elements in the specified iterable that equal the
357   * specified object. This implementation avoids a full iteration when the
358   * iterable is a {@link Multiset} or {@link Set}.
359   *
360   * @see Collections#frequency
361   */
362  public static int frequency(Iterable<?> iterable, @Nullable Object element) {
363    if ((iterable instanceof Multiset)) {
364      return ((Multiset<?>) iterable).count(element);
365    } else if ((iterable instanceof Set)) {
366      return ((Set<?>) iterable).contains(element) ? 1 : 0;
367    }
368    return Iterators.frequency(iterable.iterator(), element);
369  }
370
371  /**
372   * Returns an iterable whose iterators cycle indefinitely over the elements of
373   * {@code iterable}.
374   *
375   * <p>That iterator supports {@code remove()} if {@code iterable.iterator()}
376   * does. After {@code remove()} is called, subsequent cycles omit the removed
377   * element, which is no longer in {@code iterable}. The iterator's
378   * {@code hasNext()} method returns {@code true} until {@code iterable} is
379   * empty.
380   *
381   * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an
382   * infinite loop. You should use an explicit {@code break} or be certain that
383   * you will eventually remove all the elements.
384   *
385   * <p>To cycle over the iterable {@code n} times, use the following:
386   * {@code Iterables.concat(Collections.nCopies(n, iterable))}
387   */
388  public static <T> Iterable<T> cycle(final Iterable<T> iterable) {
389    checkNotNull(iterable);
390    return new FluentIterable<T>() {
391      @Override
392      public Iterator<T> iterator() {
393        return Iterators.cycle(iterable);
394      }
395
396      @Override
397      public String toString() {
398        return iterable.toString() + " (cycled)";
399      }
400    };
401  }
402
403  /**
404   * Returns an iterable whose iterators cycle indefinitely over the provided
405   * elements.
406   *
407   * <p>After {@code remove} is invoked on a generated iterator, the removed
408   * element will no longer appear in either that iterator or any other iterator
409   * created from the same source iterable. That is, this method behaves exactly
410   * as {@code Iterables.cycle(Lists.newArrayList(elements))}. The iterator's
411   * {@code hasNext} method returns {@code true} until all of the original
412   * elements have been removed.
413   *
414   * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an
415   * infinite loop. You should use an explicit {@code break} or be certain that
416   * you will eventually remove all the elements.
417   *
418   * <p>To cycle over the elements {@code n} times, use the following:
419   * {@code Iterables.concat(Collections.nCopies(n, Arrays.asList(elements)))}
420   */
421  public static <T> Iterable<T> cycle(T... elements) {
422    return cycle(Lists.newArrayList(elements));
423  }
424
425  /**
426   * Combines two iterables into a single iterable. The returned iterable has an
427   * iterator that traverses the elements in {@code a}, followed by the elements
428   * in {@code b}. The source iterators are not polled until necessary.
429   *
430   * <p>The returned iterable's iterator supports {@code remove()} when the
431   * corresponding input iterator supports it.
432   */
433  public static <T> Iterable<T> concat(Iterable<? extends T> a, Iterable<? extends T> b) {
434    return concat(ImmutableList.of(a, b));
435  }
436
437  /**
438   * Combines three iterables into a single iterable. The returned iterable has
439   * an iterator that traverses the elements in {@code a}, followed by the
440   * elements in {@code b}, followed by the elements in {@code c}. The source
441   * iterators are not polled until necessary.
442   *
443   * <p>The returned iterable's iterator supports {@code remove()} when the
444   * corresponding input iterator supports it.
445   */
446  public static <T> Iterable<T> concat(
447      Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c) {
448    return concat(ImmutableList.of(a, b, c));
449  }
450
451  /**
452   * Combines four iterables into a single iterable. The returned iterable has
453   * an iterator that traverses the elements in {@code a}, followed by the
454   * elements in {@code b}, followed by the elements in {@code c}, followed by
455   * the elements in {@code d}. The source iterators are not polled until
456   * necessary.
457   *
458   * <p>The returned iterable's iterator supports {@code remove()} when the
459   * corresponding input iterator supports it.
460   */
461  public static <T> Iterable<T> concat(
462      Iterable<? extends T> a,
463      Iterable<? extends T> b,
464      Iterable<? extends T> c,
465      Iterable<? extends T> d) {
466    return concat(ImmutableList.of(a, b, c, d));
467  }
468
469  /**
470   * Combines multiple iterables into a single iterable. The returned iterable
471   * has an iterator that traverses the elements of each iterable in
472   * {@code inputs}. The input iterators are not polled until necessary.
473   *
474   * <p>The returned iterable's iterator supports {@code remove()} when the
475   * corresponding input iterator supports it.
476   *
477   * @throws NullPointerException if any of the provided iterables is null
478   */
479  public static <T> Iterable<T> concat(Iterable<? extends T>... inputs) {
480    return concat(ImmutableList.copyOf(inputs));
481  }
482
483  /**
484   * Combines multiple iterables into a single iterable. The returned iterable
485   * has an iterator that traverses the elements of each iterable in
486   * {@code inputs}. The input iterators are not polled until necessary.
487   *
488   * <p>The returned iterable's iterator supports {@code remove()} when the
489   * corresponding input iterator supports it. The methods of the returned
490   * iterable may throw {@code NullPointerException} if any of the input
491   * iterators is null.
492   */
493  public static <T> Iterable<T> concat(final Iterable<? extends Iterable<? extends T>> inputs) {
494    checkNotNull(inputs);
495    return new FluentIterable<T>() {
496      @Override
497      public Iterator<T> iterator() {
498        return Iterators.concat(iterators(inputs));
499      }
500    };
501  }
502
503  /**
504   * Returns an iterator over the iterators of the given iterables.
505   */
506  private static <T> Iterator<Iterator<? extends T>> iterators(
507      Iterable<? extends Iterable<? extends T>> iterables) {
508    return new TransformedIterator<Iterable<? extends T>, Iterator<? extends T>>(
509        iterables.iterator()) {
510      @Override
511      Iterator<? extends T> transform(Iterable<? extends T> from) {
512        return from.iterator();
513      }
514    };
515  }
516
517  /**
518   * Divides an iterable into unmodifiable sublists of the given size (the final
519   * iterable may be smaller). For example, partitioning an iterable containing
520   * {@code [a, b, c, d, e]} with a partition size of 3 yields {@code
521   * [[a, b, c], [d, e]]} -- an outer iterable containing two inner lists of
522   * three and two elements, all in the original order.
523   *
524   * <p>Iterators returned by the returned iterable do not support the {@link
525   * Iterator#remove()} method. The returned lists implement {@link
526   * RandomAccess}, whether or not the input list does.
527   *
528   * <p><b>Note:</b> if {@code iterable} is a {@link List}, use {@link
529   * Lists#partition(List, int)} instead.
530   *
531   * @param iterable the iterable to return a partitioned view of
532   * @param size the desired size of each partition (the last may be smaller)
533   * @return an iterable of unmodifiable lists containing the elements of {@code
534   *     iterable} divided into partitions
535   * @throws IllegalArgumentException if {@code size} is nonpositive
536   */
537  public static <T> Iterable<List<T>> partition(final Iterable<T> iterable, final int size) {
538    checkNotNull(iterable);
539    checkArgument(size > 0);
540    return new FluentIterable<List<T>>() {
541      @Override
542      public Iterator<List<T>> iterator() {
543        return Iterators.partition(iterable.iterator(), size);
544      }
545    };
546  }
547
548  /**
549   * Divides an iterable into unmodifiable sublists of the given size, padding
550   * the final iterable with null values if necessary. For example, partitioning
551   * an iterable containing {@code [a, b, c, d, e]} with a partition size of 3
552   * yields {@code [[a, b, c], [d, e, null]]} -- an outer iterable containing
553   * two inner lists of three elements each, all in the original order.
554   *
555   * <p>Iterators returned by the returned iterable do not support the {@link
556   * Iterator#remove()} method.
557   *
558   * @param iterable the iterable to return a partitioned view of
559   * @param size the desired size of each partition
560   * @return an iterable of unmodifiable lists containing the elements of {@code
561   *     iterable} divided into partitions (the final iterable may have
562   *     trailing null elements)
563   * @throws IllegalArgumentException if {@code size} is nonpositive
564   */
565  public static <T> Iterable<List<T>> paddedPartition(final Iterable<T> iterable, final int size) {
566    checkNotNull(iterable);
567    checkArgument(size > 0);
568    return new FluentIterable<List<T>>() {
569      @Override
570      public Iterator<List<T>> iterator() {
571        return Iterators.paddedPartition(iterable.iterator(), size);
572      }
573    };
574  }
575
576  /**
577   * Returns the elements of {@code unfiltered} that satisfy a predicate. The
578   * resulting iterable's iterator does not support {@code remove()}.
579   */
580  @CheckReturnValue
581  public static <T> Iterable<T> filter(
582      final Iterable<T> unfiltered, final Predicate<? super T> predicate) {
583    checkNotNull(unfiltered);
584    checkNotNull(predicate);
585    return new FluentIterable<T>() {
586      @Override
587      public Iterator<T> iterator() {
588        return Iterators.filter(unfiltered.iterator(), predicate);
589      }
590    };
591  }
592
593  /**
594   * Returns all instances of class {@code type} in {@code unfiltered}. The
595   * returned iterable has elements whose class is {@code type} or a subclass of
596   * {@code type}. The returned iterable's iterator does not support
597   * {@code remove()}.
598   *
599   * @param unfiltered an iterable containing objects of any type
600   * @param type the type of elements desired
601   * @return an unmodifiable iterable containing all elements of the original
602   *     iterable that were of the requested type
603   */
604  @GwtIncompatible("Class.isInstance")
605  @CheckReturnValue
606  public static <T> Iterable<T> filter(final Iterable<?> unfiltered, final Class<T> type) {
607    checkNotNull(unfiltered);
608    checkNotNull(type);
609    return new FluentIterable<T>() {
610      @Override
611      public Iterator<T> iterator() {
612        return Iterators.filter(unfiltered.iterator(), type);
613      }
614    };
615  }
616
617  /**
618   * Returns {@code true} if any element in {@code iterable} satisfies the predicate.
619   */
620  public static <T> boolean any(Iterable<T> iterable, Predicate<? super T> predicate) {
621    return Iterators.any(iterable.iterator(), predicate);
622  }
623
624  /**
625   * Returns {@code true} if every element in {@code iterable} satisfies the
626   * predicate. If {@code iterable} is empty, {@code true} is returned.
627   */
628  public static <T> boolean all(Iterable<T> iterable, Predicate<? super T> predicate) {
629    return Iterators.all(iterable.iterator(), predicate);
630  }
631
632  /**
633   * Returns the first element in {@code iterable} that satisfies the given
634   * predicate; use this method only when such an element is known to exist. If
635   * it is possible that <i>no</i> element will match, use {@link #tryFind} or
636   * {@link #find(Iterable, Predicate, Object)} instead.
637   *
638   * @throws NoSuchElementException if no element in {@code iterable} matches
639   *     the given predicate
640   */
641  public static <T> T find(Iterable<T> iterable, Predicate<? super T> predicate) {
642    return Iterators.find(iterable.iterator(), predicate);
643  }
644
645  /**
646   * Returns the first element in {@code iterable} that satisfies the given
647   * predicate, or {@code defaultValue} if none found. Note that this can
648   * usually be handled more naturally using {@code
649   * tryFind(iterable, predicate).or(defaultValue)}.
650   *
651   * @since 7.0
652   */
653  @Nullable
654  public static <T> T find(
655      Iterable<? extends T> iterable, Predicate<? super T> predicate, @Nullable T defaultValue) {
656    return Iterators.find(iterable.iterator(), predicate, defaultValue);
657  }
658
659  /**
660   * Returns an {@link Optional} containing the first element in {@code
661   * iterable} that satisfies the given predicate, if such an element exists.
662   *
663   * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code
664   * null}. If {@code null} is matched in {@code iterable}, a
665   * NullPointerException will be thrown.
666   *
667   * @since 11.0
668   */
669  public static <T> Optional<T> tryFind(Iterable<T> iterable, Predicate<? super T> predicate) {
670    return Iterators.tryFind(iterable.iterator(), predicate);
671  }
672
673  /**
674   * Returns the index in {@code iterable} of the first element that satisfies
675   * the provided {@code predicate}, or {@code -1} if the Iterable has no such
676   * elements.
677   *
678   * <p>More formally, returns the lowest index {@code i} such that
679   * {@code predicate.apply(Iterables.get(iterable, i))} returns {@code true},
680   * or {@code -1} if there is no such index.
681   *
682   * @since 2.0
683   */
684  public static <T> int indexOf(Iterable<T> iterable, Predicate<? super T> predicate) {
685    return Iterators.indexOf(iterable.iterator(), predicate);
686  }
687
688  /**
689   * Returns an iterable that applies {@code function} to each element of {@code
690   * fromIterable}.
691   *
692   * <p>The returned iterable's iterator supports {@code remove()} if the
693   * provided iterator does. After a successful {@code remove()} call,
694   * {@code fromIterable} no longer contains the corresponding element.
695   *
696   * <p>If the input {@code Iterable} is known to be a {@code List} or other
697   * {@code Collection}, consider {@link Lists#transform} and {@link
698   * Collections2#transform}.
699   */
700  @CheckReturnValue
701  public static <F, T> Iterable<T> transform(
702      final Iterable<F> fromIterable, final Function<? super F, ? extends T> function) {
703    checkNotNull(fromIterable);
704    checkNotNull(function);
705    return new FluentIterable<T>() {
706      @Override
707      public Iterator<T> iterator() {
708        return Iterators.transform(fromIterable.iterator(), function);
709      }
710    };
711  }
712
713  /**
714   * Returns the element at the specified position in an iterable.
715   *
716   * @param position position of the element to return
717   * @return the element at the specified position in {@code iterable}
718   * @throws IndexOutOfBoundsException if {@code position} is negative or
719   *     greater than or equal to the size of {@code iterable}
720   */
721  public static <T> T get(Iterable<T> iterable, int position) {
722    checkNotNull(iterable);
723    return (iterable instanceof List)
724        ? ((List<T>) iterable).get(position)
725        : Iterators.get(iterable.iterator(), position);
726  }
727
728  /**
729   * Returns the element at the specified position in an iterable or a default
730   * value otherwise.
731   *
732   * @param position position of the element to return
733   * @param defaultValue the default value to return if {@code position} is
734   *     greater than or equal to the size of the iterable
735   * @return the element at the specified position in {@code iterable} or
736   *     {@code defaultValue} if {@code iterable} contains fewer than
737   *     {@code position + 1} elements.
738   * @throws IndexOutOfBoundsException if {@code position} is negative
739   * @since 4.0
740   */
741  @Nullable
742  public static <T> T get(Iterable<? extends T> iterable, int position, @Nullable T defaultValue) {
743    checkNotNull(iterable);
744    Iterators.checkNonnegative(position);
745    if (iterable instanceof List) {
746      List<? extends T> list = Lists.cast(iterable);
747      return (position < list.size()) ? list.get(position) : defaultValue;
748    } else {
749      Iterator<? extends T> iterator = iterable.iterator();
750      Iterators.advance(iterator, position);
751      return Iterators.getNext(iterator, defaultValue);
752    }
753  }
754
755  /**
756   * Returns the first element in {@code iterable} or {@code defaultValue} if
757   * the iterable is empty.  The {@link Iterators} analog to this method is
758   * {@link Iterators#getNext}.
759   *
760   * <p>If no default value is desired (and the caller instead wants a
761   * {@link NoSuchElementException} to be thrown), it is recommended that
762   * {@code iterable.iterator().next()} is used instead.
763   *
764   * @param defaultValue the default value to return if the iterable is empty
765   * @return the first element of {@code iterable} or the default value
766   * @since 7.0
767   */
768  @Nullable
769  public static <T> T getFirst(Iterable<? extends T> iterable, @Nullable T defaultValue) {
770    return Iterators.getNext(iterable.iterator(), defaultValue);
771  }
772
773  /**
774   * Returns the last element of {@code iterable}.
775   *
776   * @return the last element of {@code iterable}
777   * @throws NoSuchElementException if the iterable is empty
778   */
779  public static <T> T getLast(Iterable<T> iterable) {
780    // TODO(kevinb): Support a concurrently modified collection?
781    if (iterable instanceof List) {
782      List<T> list = (List<T>) iterable;
783      if (list.isEmpty()) {
784        throw new NoSuchElementException();
785      }
786      return getLastInNonemptyList(list);
787    }
788
789    return Iterators.getLast(iterable.iterator());
790  }
791
792  /**
793   * Returns the last element of {@code iterable} or {@code defaultValue} if
794   * the iterable is empty.
795   *
796   * @param defaultValue the value to return if {@code iterable} is empty
797   * @return the last element of {@code iterable} or the default value
798   * @since 3.0
799   */
800  @Nullable
801  public static <T> T getLast(Iterable<? extends T> iterable, @Nullable T defaultValue) {
802    if (iterable instanceof Collection) {
803      Collection<? extends T> c = Collections2.cast(iterable);
804      if (c.isEmpty()) {
805        return defaultValue;
806      } else if (iterable instanceof List) {
807        return getLastInNonemptyList(Lists.cast(iterable));
808      }
809    }
810
811    return Iterators.getLast(iterable.iterator(), defaultValue);
812  }
813
814  private static <T> T getLastInNonemptyList(List<T> list) {
815    return list.get(list.size() - 1);
816  }
817
818  /**
819   * Returns a view of {@code iterable} that skips its first
820   * {@code numberToSkip} elements. If {@code iterable} contains fewer than
821   * {@code numberToSkip} elements, the returned iterable skips all of its
822   * elements.
823   *
824   * <p>Modifications to the underlying {@link Iterable} before a call to
825   * {@code iterator()} are reflected in the returned iterator. That is, the
826   * iterator skips the first {@code numberToSkip} elements that exist when the
827   * {@code Iterator} is created, not when {@code skip()} is called.
828   *
829   * <p>The returned iterable's iterator supports {@code remove()} if the
830   * iterator of the underlying iterable supports it. Note that it is
831   * <i>not</i> possible to delete the last skipped element by immediately
832   * calling {@code remove()} on that iterator, as the {@code Iterator}
833   * contract states that a call to {@code remove()} before a call to
834   * {@code next()} will throw an {@link IllegalStateException}.
835   *
836   * @since 3.0
837   */
838  public static <T> Iterable<T> skip(final Iterable<T> iterable, final int numberToSkip) {
839    checkNotNull(iterable);
840    checkArgument(numberToSkip >= 0, "number to skip cannot be negative");
841
842    if (iterable instanceof List) {
843      final List<T> list = (List<T>) iterable;
844      return new FluentIterable<T>() {
845        @Override
846        public Iterator<T> iterator() {
847          // TODO(kevinb): Support a concurrently modified collection?
848          int toSkip = Math.min(list.size(), numberToSkip);
849          return list.subList(toSkip, list.size()).iterator();
850        }
851      };
852    }
853
854    return new FluentIterable<T>() {
855      @Override
856      public Iterator<T> iterator() {
857        final Iterator<T> iterator = iterable.iterator();
858
859        Iterators.advance(iterator, numberToSkip);
860
861        /*
862         * We can't just return the iterator because an immediate call to its
863         * remove() method would remove one of the skipped elements instead of
864         * throwing an IllegalStateException.
865         */
866        return new Iterator<T>() {
867          boolean atStart = true;
868
869          @Override
870          public boolean hasNext() {
871            return iterator.hasNext();
872          }
873
874          @Override
875          public T next() {
876            T result = iterator.next();
877            atStart = false; // not called if next() fails
878            return result;
879          }
880
881          @Override
882          public void remove() {
883            checkRemove(!atStart);
884            iterator.remove();
885          }
886        };
887      }
888    };
889  }
890
891  /**
892   * Creates an iterable with the first {@code limitSize} elements of the given
893   * iterable. If the original iterable does not contain that many elements, the
894   * returned iterable will have the same behavior as the original iterable. The
895   * returned iterable's iterator supports {@code remove()} if the original
896   * iterator does.
897   *
898   * @param iterable the iterable to limit
899   * @param limitSize the maximum number of elements in the returned iterable
900   * @throws IllegalArgumentException if {@code limitSize} is negative
901   * @since 3.0
902   */
903  public static <T> Iterable<T> limit(final Iterable<T> iterable, final int limitSize) {
904    checkNotNull(iterable);
905    checkArgument(limitSize >= 0, "limit is negative");
906    return new FluentIterable<T>() {
907      @Override
908      public Iterator<T> iterator() {
909        return Iterators.limit(iterable.iterator(), limitSize);
910      }
911    };
912  }
913
914  /**
915   * Returns a view of the supplied iterable that wraps each generated
916   * {@link Iterator} through {@link Iterators#consumingIterator(Iterator)}.
917   *
918   * <p>Note: If {@code iterable} is a {@link Queue}, the returned iterable will
919   * get entries from {@link Queue#remove()} since {@link Queue}'s iteration
920   * order is undefined.  Calling {@link Iterator#hasNext()} on a generated
921   * iterator from the returned iterable may cause an item to be immediately
922   * dequeued for return on a subsequent call to {@link Iterator#next()}.
923   *
924   * @param iterable the iterable to wrap
925   * @return a view of the supplied iterable that wraps each generated iterator
926   *     through {@link Iterators#consumingIterator(Iterator)}; for queues,
927   *     an iterable that generates iterators that return and consume the
928   *     queue's elements in queue order
929   *
930   * @see Iterators#consumingIterator(Iterator)
931   * @since 2.0
932   */
933  public static <T> Iterable<T> consumingIterable(final Iterable<T> iterable) {
934    if (iterable instanceof Queue) {
935      return new FluentIterable<T>() {
936        @Override
937        public Iterator<T> iterator() {
938          return new ConsumingQueueIterator<T>((Queue<T>) iterable);
939        }
940
941        @Override
942        public String toString() {
943          return "Iterables.consumingIterable(...)";
944        }
945      };
946    }
947
948    checkNotNull(iterable);
949
950    return new FluentIterable<T>() {
951      @Override
952      public Iterator<T> iterator() {
953        return Iterators.consumingIterator(iterable.iterator());
954      }
955
956      @Override
957      public String toString() {
958        return "Iterables.consumingIterable(...)";
959      }
960    };
961  }
962
963  // Methods only in Iterables, not in Iterators
964
965  /**
966   * Determines if the given iterable contains no elements.
967   *
968   * <p>There is no precise {@link Iterator} equivalent to this method, since
969   * one can only ask an iterator whether it has any elements <i>remaining</i>
970   * (which one does using {@link Iterator#hasNext}).
971   *
972   * @return {@code true} if the iterable contains no elements
973   */
974  public static boolean isEmpty(Iterable<?> iterable) {
975    if (iterable instanceof Collection) {
976      return ((Collection<?>) iterable).isEmpty();
977    }
978    return !iterable.iterator().hasNext();
979  }
980
981  /**
982   * Returns an iterable over the merged contents of all given
983   * {@code iterables}. Equivalent entries will not be de-duplicated.
984   *
985   * <p>Callers must ensure that the source {@code iterables} are in
986   * non-descending order as this method does not sort its input.
987   *
988   * <p>For any equivalent elements across all {@code iterables}, it is
989   * undefined which element is returned first.
990   *
991   * @since 11.0
992   */
993  @Beta
994  public static <T> Iterable<T> mergeSorted(
995      final Iterable<? extends Iterable<? extends T>> iterables,
996      final Comparator<? super T> comparator) {
997    checkNotNull(iterables, "iterables");
998    checkNotNull(comparator, "comparator");
999    Iterable<T> iterable =
1000        new FluentIterable<T>() {
1001          @Override
1002          public Iterator<T> iterator() {
1003            return Iterators.mergeSorted(
1004                Iterables.transform(iterables, Iterables.<T>toIterator()),
1005                comparator);
1006          }
1007        };
1008    return new UnmodifiableIterable<T>(iterable);
1009  }
1010
1011  // TODO(user): Is this the best place for this? Move to fluent functions?
1012  // Useful as a public method?
1013  private static <T> Function<Iterable<? extends T>, Iterator<? extends T>> toIterator() {
1014    return new Function<Iterable<? extends T>, Iterator<? extends T>>() {
1015      @Override
1016      public Iterator<? extends T> apply(Iterable<? extends T> iterable) {
1017        return iterable.iterator();
1018      }
1019    };
1020  }
1021}