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