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