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