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