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