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        @Override
095        public Iterator<T> iterator() {
096          return Iterators.unmodifiableIterator(iterable.iterator());
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          @Override
375          public Iterator<T> iterator() {
376            return Iterators.cycle(iterable);
377          }
378          @Override public String toString() {
379            return iterable.toString() + " (cycled)";
380          }
381        };
382      }
383    
384      /**
385       * Returns an iterable whose iterators cycle indefinitely over the provided
386       * elements.
387       *
388       * <p>After {@code remove} is invoked on a generated iterator, the removed
389       * element will no longer appear in either that iterator or any other iterator
390       * created from the same source iterable. That is, this method behaves exactly
391       * as {@code Iterables.cycle(Lists.newArrayList(elements))}. The iterator's
392       * {@code hasNext} method returns {@code true} until all of the original
393       * elements have been removed.
394       *
395       * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an
396       * infinite loop. You should use an explicit {@code break} or be certain that
397       * you will eventually remove all the elements.
398       *
399       * <p>To cycle over the elements {@code n} times, use the following:
400       * {@code Iterables.concat(Collections.nCopies(n, Arrays.asList(elements)))}
401       */
402      public static <T> Iterable<T> cycle(T... elements) {
403        return cycle(Lists.newArrayList(elements));
404      }
405    
406      /**
407       * Combines two iterables into a single iterable. The returned iterable has an
408       * iterator that traverses the elements in {@code a}, followed by the elements
409       * in {@code b}. The source iterators are not polled until necessary.
410       *
411       * <p>The returned iterable's iterator supports {@code remove()} when the
412       * corresponding input iterator supports it.
413       */
414      @SuppressWarnings("unchecked")
415      public static <T> Iterable<T> concat(
416          Iterable<? extends T> a, Iterable<? extends T> b) {
417        checkNotNull(a);
418        checkNotNull(b);
419        return concat(Arrays.asList(a, b));
420      }
421    
422      /**
423       * Combines three iterables into a single iterable. The returned iterable has
424       * an iterator that traverses the elements in {@code a}, followed by the
425       * elements in {@code b}, followed by the elements in {@code c}. The source
426       * iterators are not polled until necessary.
427       *
428       * <p>The returned iterable's iterator supports {@code remove()} when the
429       * corresponding input iterator supports it.
430       */
431      @SuppressWarnings("unchecked")
432      public static <T> Iterable<T> concat(Iterable<? extends T> a,
433          Iterable<? extends T> b, Iterable<? extends T> c) {
434        checkNotNull(a);
435        checkNotNull(b);
436        checkNotNull(c);
437        return concat(Arrays.asList(a, b, c));
438      }
439    
440      /**
441       * Combines four iterables into a single iterable. The returned iterable has
442       * an iterator that traverses the elements in {@code a}, followed by the
443       * elements in {@code b}, followed by the elements in {@code c}, followed by
444       * the elements in {@code d}. The source iterators are not polled until
445       * necessary.
446       *
447       * <p>The returned iterable's iterator supports {@code remove()} when the
448       * corresponding input iterator supports it.
449       */
450      @SuppressWarnings("unchecked")
451      public static <T> Iterable<T> concat(Iterable<? extends T> a,
452          Iterable<? extends T> b, Iterable<? extends T> c,
453          Iterable<? extends T> d) {
454        checkNotNull(a);
455        checkNotNull(b);
456        checkNotNull(c);
457        checkNotNull(d);
458        return concat(Arrays.asList(a, b, c, d));
459      }
460    
461      /**
462       * Combines multiple iterables into a single iterable. The returned iterable
463       * has an iterator that traverses the elements of each iterable in
464       * {@code inputs}. The input iterators are not polled until necessary.
465       *
466       * <p>The returned iterable's iterator supports {@code remove()} when the
467       * corresponding input iterator supports it.
468       *
469       * @throws NullPointerException if any of the provided iterables is null
470       */
471      public static <T> Iterable<T> concat(Iterable<? extends T>... inputs) {
472        return concat(ImmutableList.copyOf(inputs));
473      }
474    
475      /**
476       * Combines multiple iterables into a single iterable. The returned iterable
477       * has an iterator that traverses the elements of each iterable in
478       * {@code inputs}. The input iterators are not polled until necessary.
479       *
480       * <p>The returned iterable's iterator supports {@code remove()} when the
481       * corresponding input iterator supports it. The methods of the returned
482       * iterable may throw {@code NullPointerException} if any of the input
483       * iterators is null.
484       */
485      public static <T> Iterable<T> concat(
486          final Iterable<? extends Iterable<? extends T>> inputs) {
487        checkNotNull(inputs);
488        return new FluentIterable<T>() {
489          @Override
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          @Override
505          public boolean hasNext() {
506            return iterableIterator.hasNext();
507          }
508          @Override
509          public Iterator<? extends T> next() {
510            return iterableIterator.next().iterator();
511          }
512        };
513      }
514    
515      /**
516       * Divides an iterable into unmodifiable sublists of the given size (the final
517       * iterable may be smaller). For example, partitioning an iterable containing
518       * {@code [a, b, c, d, e]} with a partition size of 3 yields {@code
519       * [[a, b, c], [d, e]]} -- an outer iterable containing two inner lists of
520       * three and two elements, all in the original order.
521       *
522       * <p>Iterators returned by the returned iterable do not support the {@link
523       * Iterator#remove()} method. The returned lists implement {@link
524       * RandomAccess}, whether or not the input list does.
525       *
526       * <p><b>Note:</b> if {@code iterable} is a {@link List}, use {@link
527       * Lists#partition(List, int)} instead.
528       *
529       * @param iterable the iterable to return a partitioned view of
530       * @param size the desired size of each partition (the last may be smaller)
531       * @return an iterable of unmodifiable lists containing the elements of {@code
532       *     iterable} divided into partitions
533       * @throws IllegalArgumentException if {@code size} is nonpositive
534       */
535      public static <T> Iterable<List<T>> partition(
536          final Iterable<T> iterable, final int size) {
537        checkNotNull(iterable);
538        checkArgument(size > 0);
539        return new FluentIterable<List<T>>() {
540          @Override
541          public Iterator<List<T>> iterator() {
542            return Iterators.partition(iterable.iterator(), size);
543          }
544        };
545      }
546    
547      /**
548       * Divides an iterable into unmodifiable sublists of the given size, padding
549       * the final iterable with null values if necessary. For example, partitioning
550       * an iterable containing {@code [a, b, c, d, e]} with a partition size of 3
551       * yields {@code [[a, b, c], [d, e, null]]} -- an outer iterable containing
552       * two inner lists of three elements each, all in the original order.
553       *
554       * <p>Iterators returned by the returned iterable do not support the {@link
555       * Iterator#remove()} method.
556       *
557       * @param iterable the iterable to return a partitioned view of
558       * @param size the desired size of each partition
559       * @return an iterable of unmodifiable lists containing the elements of {@code
560       *     iterable} divided into partitions (the final iterable may have
561       *     trailing null elements)
562       * @throws IllegalArgumentException if {@code size} is nonpositive
563       */
564      public static <T> Iterable<List<T>> paddedPartition(
565          final Iterable<T> iterable, final int size) {
566        checkNotNull(iterable);
567        checkArgument(size > 0);
568        return new FluentIterable<List<T>>() {
569          @Override
570          public Iterator<List<T>> iterator() {
571            return Iterators.paddedPartition(iterable.iterator(), size);
572          }
573        };
574      }
575    
576      /**
577       * Returns the elements of {@code unfiltered} that satisfy a predicate. The
578       * resulting iterable's iterator does not support {@code remove()}.
579       */
580      public static <T> Iterable<T> filter(
581          final Iterable<T> unfiltered, final Predicate<? super T> predicate) {
582        checkNotNull(unfiltered);
583        checkNotNull(predicate);
584        return new FluentIterable<T>() {
585          @Override
586          public Iterator<T> iterator() {
587            return Iterators.filter(unfiltered.iterator(), predicate);
588          }
589        };
590      }
591    
592      /**
593       * Returns all instances of class {@code type} in {@code unfiltered}. The
594       * returned iterable has elements whose class is {@code type} or a subclass of
595       * {@code type}. The returned iterable's iterator does not support
596       * {@code remove()}.
597       *
598       * @param unfiltered an iterable containing objects of any type
599       * @param type the type of elements desired
600       * @return an unmodifiable iterable containing all elements of the original
601       *     iterable that were of the requested type
602       */
603      @GwtIncompatible("Class.isInstance")
604      public static <T> Iterable<T> filter(
605          final Iterable<?> unfiltered, final Class<T> type) {
606        checkNotNull(unfiltered);
607        checkNotNull(type);
608        return new FluentIterable<T>() {
609          @Override
610          public Iterator<T> iterator() {
611            return Iterators.filter(unfiltered.iterator(), type);
612          }
613        };
614      }
615    
616      /**
617       * Returns {@code true} if any element in {@code iterable} satisfies the predicate.
618       */
619      public static <T> boolean any(
620          Iterable<T> iterable, Predicate<? super T> predicate) {
621        return Iterators.any(iterable.iterator(), predicate);
622      }
623    
624      /**
625       * Returns {@code true} if every element in {@code iterable} satisfies the
626       * predicate. If {@code iterable} is empty, {@code true} is returned.
627       */
628      public static <T> boolean all(
629          Iterable<T> iterable, Predicate<? super T> predicate) {
630        return Iterators.all(iterable.iterator(), predicate);
631      }
632    
633      /**
634       * Returns the first element in {@code iterable} that satisfies the given
635       * predicate; use this method only when such an element is known to exist. If
636       * it is possible that <i>no</i> element will match, use {@link #tryFind} or
637       * {@link #find(Iterable, Predicate, Object)} instead.
638       *
639       * @throws NoSuchElementException if no element in {@code iterable} matches
640       *     the given predicate
641       */
642      public static <T> T find(Iterable<T> iterable,
643          Predicate<? super T> predicate) {
644        return Iterators.find(iterable.iterator(), predicate);
645      }
646    
647      /**
648       * Returns the first element in {@code iterable} that satisfies the given
649       * predicate, or {@code defaultValue} if none found. Note that this can
650       * usually be handled more naturally using {@code
651       * tryFind(iterable, predicate).or(defaultValue)}.
652       *
653       * @since 7.0
654       */
655      public static <T> T find(Iterable<? extends T> iterable,
656          Predicate<? super T> predicate, @Nullable T defaultValue) {
657        return Iterators.find(iterable.iterator(), predicate, defaultValue);
658      }
659    
660      /**
661       * Returns an {@link Optional} containing the first element in {@code
662       * iterable} that satisfies the given predicate, if such an element exists.
663       *
664       * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code
665       * null}. If {@code null} is matched in {@code iterable}, a
666       * NullPointerException will be thrown.
667       *
668       * @since 11.0
669       */
670      public static <T> Optional<T> tryFind(Iterable<T> iterable,
671          Predicate<? super T> predicate) {
672        return Iterators.tryFind(iterable.iterator(), predicate);
673      }
674    
675      /**
676       * Returns the index in {@code iterable} of the first element that satisfies
677       * the provided {@code predicate}, or {@code -1} if the Iterable has no such
678       * elements.
679       *
680       * <p>More formally, returns the lowest index {@code i} such that
681       * {@code predicate.apply(Iterables.get(iterable, i))} returns {@code true},
682       * or {@code -1} if there is no such index.
683       *
684       * @since 2.0
685       */
686      public static <T> int indexOf(
687          Iterable<T> iterable, Predicate<? super T> predicate) {
688        return Iterators.indexOf(iterable.iterator(), predicate);
689      }
690    
691      /**
692       * Returns an iterable that applies {@code function} to each element of {@code
693       * fromIterable}.
694       *
695       * <p>The returned iterable's iterator supports {@code remove()} if the
696       * provided iterator does. After a successful {@code remove()} call,
697       * {@code fromIterable} no longer contains the corresponding element.
698       *
699       * <p>If the input {@code Iterable} is known to be a {@code List} or other
700       * {@code Collection}, consider {@link Lists#transform} and {@link
701       * Collections2#transform}.
702       */
703      public static <F, T> Iterable<T> transform(final Iterable<F> fromIterable,
704          final Function<? super F, ? extends T> function) {
705        checkNotNull(fromIterable);
706        checkNotNull(function);
707        return new FluentIterable<T>() {
708          @Override
709          public Iterator<T> iterator() {
710            return Iterators.transform(fromIterable.iterator(), function);
711          }
712        };
713      }
714    
715      /**
716       * Returns the element at the specified position in an iterable.
717       *
718       * @param position position of the element to return
719       * @return the element at the specified position in {@code iterable}
720       * @throws IndexOutOfBoundsException if {@code position} is negative or
721       *     greater than or equal to the size of {@code iterable}
722       */
723      public static <T> T get(Iterable<T> iterable, int position) {
724        checkNotNull(iterable);
725        if (iterable instanceof List) {
726          return ((List<T>) iterable).get(position);
727        }
728    
729        if (iterable instanceof Collection) {
730          // Can check both ends
731          Collection<T> collection = (Collection<T>) iterable;
732          Preconditions.checkElementIndex(position, collection.size());
733        } else {
734          // Can only check the lower end
735          checkNonnegativeIndex(position);
736        }
737        return Iterators.get(iterable.iterator(), position);
738      }
739    
740      private static void checkNonnegativeIndex(int position) {
741        if (position < 0) {
742          throw new IndexOutOfBoundsException(
743              "position cannot be negative: " + position);
744        }
745      }
746    
747      /**
748       * Returns the element at the specified position in an iterable or a default
749       * value otherwise.
750       *
751       * @param position position of the element to return
752       * @param defaultValue the default value to return if {@code position} is
753       *     greater than or equal to the size of the iterable
754       * @return the element at the specified position in {@code iterable} or
755       *     {@code defaultValue} if {@code iterable} contains fewer than
756       *     {@code position + 1} elements.
757       * @throws IndexOutOfBoundsException if {@code position} is negative
758       * @since 4.0
759       */
760      public static <T> T get(Iterable<? extends T> iterable, int position, @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<? extends 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<? extends T> iterable, @Nullable T defaultValue) {
822        if (iterable instanceof Collection) {
823          Collection<? extends T> collection = Collections2.cast(iterable);
824          if (collection.isEmpty()) {
825            return defaultValue;
826          }
827        }
828    
829        if (iterable instanceof List) {
830          List<? extends T> list = Lists.cast(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<? extends T> sortedSet = Sets.cast(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 FluentIterable<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 FluentIterable<T>() {
890          @Override
891          public Iterator<T> iterator() {
892            final Iterator<T> iterator = iterable.iterator();
893    
894            Iterators.advance(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 FluentIterable<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 FluentIterable<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 FluentIterable<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       * Determines if the given iterable contains no elements.
1017       *
1018       * <p>There is no precise {@link Iterator} equivalent to this method, since
1019       * one can only ask an iterator whether it has any elements <i>remaining</i>
1020       * (which one does using {@link Iterator#hasNext}).
1021       *
1022       * @return {@code true} if the iterable contains no elements
1023       */
1024      public static boolean isEmpty(Iterable<?> iterable) {
1025        if (iterable instanceof Collection) {
1026          return ((Collection<?>) iterable).isEmpty();
1027        }
1028        return !iterable.iterator().hasNext();
1029      }
1030    
1031      /**
1032       * Returns an iterable over the merged contents of all given
1033       * {@code iterables}. Equivalent entries will not be de-duplicated.
1034       *
1035       * <p>Callers must ensure that the source {@code iterables} are in
1036       * non-descending order as this method does not sort its input.
1037       *
1038       * <p>For any equivalent elements across all {@code iterables}, it is
1039       * undefined which element is returned first.
1040       *
1041       * @since 11.0
1042       */
1043      @Beta
1044      public static <T> Iterable<T> mergeSorted(
1045          final Iterable<? extends Iterable<? extends T>> iterables,
1046          final Comparator<? super T> comparator) {
1047        checkNotNull(iterables, "iterables");
1048        checkNotNull(comparator, "comparator");
1049        Iterable<T> iterable = new FluentIterable<T>() {
1050          @Override
1051          public Iterator<T> iterator() {
1052            return Iterators.mergeSorted(
1053                Iterables.transform(iterables, Iterables.<T>toIterator()),
1054                comparator);
1055          }
1056        };
1057        return new UnmodifiableIterable<T>(iterable);
1058      }
1059    
1060      // TODO(user): Is this the best place for this? Move to fluent functions?
1061      // Useful as a public method?
1062      private static <T> Function<Iterable<? extends T>, Iterator<? extends T>>
1063          toIterator() {
1064        return new Function<Iterable<? extends T>, Iterator<? extends T>>() {
1065          @Override
1066          public Iterator<? extends T> apply(Iterable<? extends T> iterable) {
1067            return iterable.iterator();
1068          }
1069        };
1070      }
1071    }