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