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