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