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