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