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