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