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