001/*
002 * Copyright (C) 2008 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.collect;
016
017import static com.google.common.base.Preconditions.checkNotNull;
018
019import com.google.common.annotations.Beta;
020import com.google.common.annotations.GwtCompatible;
021import com.google.common.annotations.GwtIncompatible;
022import com.google.common.base.Function;
023import com.google.common.base.Joiner;
024import com.google.common.base.Optional;
025import com.google.common.base.Predicate;
026import com.google.errorprone.annotations.CanIgnoreReturnValue;
027import java.util.Arrays;
028import java.util.Collection;
029import java.util.Comparator;
030import java.util.Iterator;
031import java.util.List;
032import java.util.SortedSet;
033import javax.annotation.Nullable;
034
035/**
036 * An expanded {@code Iterable} API, providing functionality similar to Java 8's powerful <a href=
037 * "https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#package.description"
038 * >streams library</a> in a slightly different way.
039 *
040 * <p>The following types of methods are provided:
041 *
042 * <ul>
043 * <li>chaining methods which return a new {@code FluentIterable} based in some way on the contents
044 *     of the current one (for example {@link #transform})
045 * <li>element extraction methods which facilitate the retrieval of certain elements (for example
046 *     {@link #last})
047 * <li>query methods which answer questions about the {@code FluentIterable}'s contents (for example
048 *     {@link #anyMatch})
049 * <li>conversion methods which copy the {@code FluentIterable}'s contents into a new collection or
050 *     array (for example {@link #toList})
051 * </ul>
052 *
053 * <p>Several lesser-used features are currently available only as static methods on the {@link
054 * Iterables} class.
055 *
056 * <a name="streams"></a>
057 * <h3>Comparison to streams</h3>
058 *
059 * <p>Starting with Java 8, the core Java class libraries provide a new "Streams" library (in {@code
060 * java.util.stream}), which is similar to {@code FluentIterable} but generally more powerful. Key
061 * differences include:</b>
062 *
063 * <ul>
064 * <li>A stream is <i>single-use</i>; it becomes invalid as soon as any "terminal operation" such as
065 *     {@code findFirst()} or {@code iterator()} is invoked. (Even though {@code Stream} contains
066 *     all the right method <i>signatures</i> to implement {@link Iterable}, it does not actually do
067 *     so, to avoid implying repeat-iterability.) {@code FluentIterable}, on the other hand, is
068 *     multiple-use, and does implement {@link Iterable}.
069 * <li>Streams offer many features not found here, including {@code min/max}, {@code distinct},
070 *     {@code reduce}, {@code sorted}, the very powerful {@code collect}, and built-in support for
071 *     parallelizing stream operations.
072 * <li>{@code FluentIterable} contains several features not available on {@code Stream}, which are
073 *     noted in the method descriptions below.
074 * <li>Streams include primitive-specialized variants such as {@code IntStream}, the use of which is
075 *     strongly recommended.
076 * <li>Streams are standard Java, not requiring a third-party dependency (but do render your code
077 *     incompatible with Java 7 and earlier).
078 * </ul>
079 *
080 * <h3>Example</h3>
081 *
082 * <p>Here is an example that accepts a list from a database call, filters it based on a predicate,
083 * transforms it by invoking {@code toString()} on each element, and returns the first 10 elements
084 * as a {@code List}:
085 *
086 * <pre>{@code
087 * ImmutableList<String> results =
088 *     FluentIterable.from(database.getClientList())
089 *         .filter(Client::isActiveInLastMonth)
090 *         .transform(Object::toString)
091 *         .limit(10)
092 *         .toList();
093 * }</pre>
094 *
095 * The approximate stream equivalent is:
096 *
097 * <pre>{@code
098 * List<String> results =
099 *     database.getClientList()
100 *         .stream()
101 *         .filter(Client::isActiveInLastMonth)
102 *         .map(Object::toString)
103 *         .limit(10)
104 *         .collect(Collectors.toList());
105 * }</pre>
106 *
107 * @author Marcin Mikosik
108 * @since 12.0
109 */
110@GwtCompatible(emulated = true)
111public abstract class FluentIterable<E> implements Iterable<E> {
112  // We store 'iterable' and use it instead of 'this' to allow Iterables to perform instanceof
113  // checks on the _original_ iterable when FluentIterable.from is used.
114  // To avoid a self retain cycle under j2objc, we store Optional.absent() instead of
115  // Optional.of(this). To access the iterator delegate, call #getDelegate(), which converts to
116  // absent() back to 'this'.
117  private final Optional<Iterable<E>> iterableDelegate;
118
119  /** Constructor for use by subclasses. */
120  protected FluentIterable() {
121    this.iterableDelegate = Optional.absent();
122  }
123
124  FluentIterable(Iterable<E> iterable) {
125    checkNotNull(iterable);
126    this.iterableDelegate = Optional.fromNullable(this != iterable ? iterable : null);
127  }
128
129  private Iterable<E> getDelegate() {
130    return iterableDelegate.or(this);
131  }
132
133  /**
134   * Returns a fluent iterable that wraps {@code iterable}, or {@code iterable} itself if it is
135   * already a {@code FluentIterable}.
136   *
137   * <p><b>{@code Stream} equivalent:</b> {@code iterable.stream()} if {@code iterable} is a
138   * {@link Collection}; {@code StreamSupport.stream(iterable.spliterator(), false)} otherwise.
139   */
140  public static <E> FluentIterable<E> from(final Iterable<E> iterable) {
141    return (iterable instanceof FluentIterable)
142        ? (FluentIterable<E>) iterable
143        : new FluentIterable<E>(iterable) {
144          @Override
145          public Iterator<E> iterator() {
146            return iterable.iterator();
147          }
148        };
149  }
150
151  /**
152   * Returns a fluent iterable containing {@code elements} in the specified order.
153   *
154   * <p>The returned iterable is an unmodifiable view of the input array.
155   *
156   * <p><b>{@code Stream} equivalent:</b> {@link Stream#of(T...)}.
157   *
158   * @since 20.0 (since 18.0 as an overload of {@code of})
159   */
160  @Beta
161  public static <E> FluentIterable<E> from(E[] elements) {
162    return from(Arrays.asList(elements));
163  }
164
165  /**
166   * Construct a fluent iterable from another fluent iterable. This is obviously never necessary,
167   * but is intended to help call out cases where one migration from {@code Iterable} to
168   * {@code FluentIterable} has obviated the need to explicitly convert to a {@code FluentIterable}.
169   *
170   * @deprecated instances of {@code FluentIterable} don't need to be converted to
171   *     {@code FluentIterable}
172   */
173  @Deprecated
174  public static <E> FluentIterable<E> from(FluentIterable<E> iterable) {
175    return checkNotNull(iterable);
176  }
177
178  /**
179   * Returns a fluent iterable that combines two iterables. The returned iterable has an iterator
180   * that traverses the elements in {@code a}, followed by the elements in {@code b}. The source
181   * iterators are not polled until necessary.
182   *
183   * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input
184   * iterator supports it.
185   *
186   * <p><b>{@code Stream} equivalent:</b> {@link Stream#concat}.
187   *
188   * @since 20.0
189   */
190  @Beta
191  public static <T> FluentIterable<T> concat(Iterable<? extends T> a, Iterable<? extends T> b) {
192    return concat(ImmutableList.of(a, b));
193  }
194
195  /**
196   * Returns a fluent iterable that combines three iterables. The returned iterable has an iterator
197   * that traverses the elements in {@code a}, followed by the elements in {@code b}, followed by
198   * the elements in {@code c}. The source iterators are not polled until necessary.
199   *
200   * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input
201   * iterator supports it.
202   *
203   * <p><b>{@code Stream} equivalent:</b> use nested calls to {@link Stream#concat}, or see the
204   * advice in {@link #concat(Iterable...)}.
205   *
206   * @since 20.0
207   */
208  @Beta
209  public static <T> FluentIterable<T> concat(
210      Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c) {
211    return concat(ImmutableList.of(a, b, c));
212  }
213
214  /**
215   * Returns a fluent iterable that combines four iterables. The returned iterable has an iterator
216   * that traverses the elements in {@code a}, followed by the elements in {@code b}, followed by
217   * the elements in {@code c}, followed by the elements in {@code d}. The source iterators are not
218   * polled until necessary.
219   *
220   * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input
221   * iterator supports it.
222   *
223   * <p><b>{@code Stream} equivalent:</b> use nested calls to {@link Stream#concat}, or see the
224   * advice in {@link #concat(Iterable...)}.
225   *
226   * @since 20.0
227   */
228  @Beta
229  public static <T> FluentIterable<T> concat(
230      Iterable<? extends T> a,
231      Iterable<? extends T> b,
232      Iterable<? extends T> c,
233      Iterable<? extends T> d) {
234    return concat(ImmutableList.of(a, b, c, d));
235  }
236
237  /**
238   * Returns a fluent iterable that combines several iterables. The returned iterable has an
239   * iterator that traverses the elements of each iterable in {@code inputs}. The input iterators
240   * are not polled until necessary.
241   *
242   * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input
243   * iterator supports it.
244   *
245   * <p><b>{@code Stream} equivalent:</b> to concatenate an arbitrary number of streams, use {@code
246   * Stream.of(stream1, stream2, ...).flatMap(s -> s)}. If the sources are iterables, after the next
247   * release of Guava you can use {@code Stream.of(iter1, iter2, ...).flatMap(Streams::stream)}.
248   *
249   * @throws NullPointerException if any of the provided iterables is {@code null}
250   * @since 20.0
251   */
252  @Beta
253  public static <T> FluentIterable<T> concat(Iterable<? extends T>... inputs) {
254    return concat(ImmutableList.copyOf(inputs));
255  }
256
257  /**
258   * Returns a fluent iterable that combines several iterables. The returned iterable has an
259   * iterator that traverses the elements of each iterable in {@code inputs}. The input iterators
260   * are not polled until necessary.
261   *
262   * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input
263   * iterator supports it. The methods of the returned iterable may throw {@code
264   * NullPointerException} if any of the input iterators is {@code null}.
265   *
266   * <p><b>{@code Stream} equivalent:</b> {@code streamOfStreams.flatMap(s -> s)} or {@code
267   * streamOfIterables.flatMap(Streams::stream)}. (See {@link Streams#stream}.)
268   *
269   * @since 20.0
270   */
271  @Beta
272  public static <T> FluentIterable<T> concat(
273      final Iterable<? extends Iterable<? extends T>> inputs) {
274    checkNotNull(inputs);
275    return new FluentIterable<T>() {
276      @Override
277      public Iterator<T> iterator() {
278        return Iterators.concat(Iterables.transform(inputs, Iterables.<T>toIterator()).iterator());
279      }
280    };
281  }
282
283  /**
284   * Returns a fluent iterable containing no elements.
285   *
286   * <p><b>{@code Stream} equivalent:</b> {@code Stream.empty()}.
287   *
288   * @since 20.0
289   */
290  @Beta
291  public static <E> FluentIterable<E> of() {
292    return FluentIterable.from(ImmutableList.<E>of());
293  }
294
295  /**
296   * Returns a fluent iterable containing {@code elements} in the specified order.
297   *
298   * <p>The returned iterable is modifiable, but modifications do not affect the input array.
299   *
300   * <p><b>{@code Stream} equivalent:</b> {@link Stream#of(T...)}.
301   *
302   * @deprecated Use {@link #from(E[])} instead (but note the differences in mutability). This
303   *     method will be removed in Guava release 21.0.
304   * @since 18.0
305   */
306  @Beta
307  @Deprecated
308  public static <E> FluentIterable<E> of(E[] elements) {
309    return from(Lists.newArrayList(elements));
310  }
311
312  /**
313   * Returns a fluent iterable containing the specified elements in order.
314   *
315   * <p><b>{@code Stream} equivalent:</b> {@link Stream#of(T...)}.
316   *
317   * @since 20.0
318   */
319  @Beta
320  public static <E> FluentIterable<E> of(@Nullable E element, E... elements) {
321    return from(Lists.asList(element, elements));
322  }
323
324  /**
325   * Returns a string representation of this fluent iterable, with the format {@code [e1, e2, ...,
326   * en]}.
327   *
328   * <p><b>{@code Stream} equivalent:</b> {@code stream.collect(Collectors.joining(", ", "[", "]"))}
329   * or (less efficiently) {@code stream.collect(Collectors.toList()).toString()}.
330   */
331  @Override
332  public String toString() {
333    return Iterables.toString(getDelegate());
334  }
335
336  /**
337   * Returns the number of elements in this fluent iterable.
338   *
339   * <p><b>{@code Stream} equivalent:</b> {@code stream.count()}.
340   */
341  public final int size() {
342    return Iterables.size(getDelegate());
343  }
344
345  /**
346   * Returns {@code true} if this fluent iterable contains any object for which
347   * {@code equals(target)} is true.
348   *
349   * <p><b>{@code Stream} equivalent:</b> {@code stream.anyMatch(Predicate.isEqual(target))}.
350   */
351  public final boolean contains(@Nullable Object target) {
352    return Iterables.contains(getDelegate(), target);
353  }
354
355  /**
356   * Returns a fluent iterable whose {@code Iterator} cycles indefinitely over the elements of this
357   * fluent iterable.
358   *
359   * <p>That iterator supports {@code remove()} if {@code iterable.iterator()} does. After
360   * {@code remove()} is called, subsequent cycles omit the removed element, which is no longer in
361   * this fluent iterable. The iterator's {@code hasNext()} method returns {@code true} until this
362   * fluent iterable is empty.
363   *
364   * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You
365   * should use an explicit {@code break} or be certain that you will eventually remove all the
366   * elements.
367   *
368   * <p><b>{@code Stream} equivalent:</b> if the source iterable has only a single element {@code
369   * element}, use {@code Stream.generate(() -> element)}. Otherwise, if the source iterable has a
370   * {@code stream} method (for example, if it is a {@link Collection}), use
371   * {@code Stream.generate(iterable::stream).flatMap(s -> s)}.
372   */
373  public final FluentIterable<E> cycle() {
374    return from(Iterables.cycle(getDelegate()));
375  }
376
377  /**
378   * Returns a fluent iterable whose iterators traverse first the elements of this fluent iterable,
379   * followed by those of {@code other}. The iterators are not polled until necessary.
380   *
381   * <p>The returned iterable's {@code Iterator} supports {@code remove()} when the corresponding
382   * {@code Iterator} supports it.
383   *
384   * <p><b>{@code Stream} equivalent:</b> {@link Stream#concat}.
385   *
386   * @since 18.0
387   */
388  @Beta
389  public final FluentIterable<E> append(Iterable<? extends E> other) {
390    return from(FluentIterable.concat(getDelegate(), other));
391  }
392
393  /**
394   * Returns a fluent iterable whose iterators traverse first the elements of this fluent iterable,
395   * followed by {@code elements}.
396   *
397   * <p><b>{@code Stream} equivalent:</b> {@code Stream.concat(thisStream, Stream.of(elements))}.
398   *
399   * @since 18.0
400   */
401  @Beta
402  public final FluentIterable<E> append(E... elements) {
403    return from(FluentIterable.concat(getDelegate(), Arrays.asList(elements)));
404  }
405
406  /**
407   * Returns the elements from this fluent iterable that satisfy a predicate. The resulting fluent
408   * iterable's iterator does not support {@code remove()}.
409   *
410   * <p><b>{@code Stream} equivalent:</b> {@link Stream#filter} (same).
411   */
412  public final FluentIterable<E> filter(Predicate<? super E> predicate) {
413    return from(Iterables.filter(getDelegate(), predicate));
414  }
415
416  /**
417   * Returns the elements from this fluent iterable that are instances of class {@code type}.
418   *
419   * <p><b>{@code Stream} equivalent:</b> {@code stream.filter(type::isInstance).map(type::cast)}.
420   * This does perform a little more work than necessary, so another option is to insert an
421   * unchecked cast at some later point:
422   *
423   * <pre>
424   * {@code @SuppressWarnings("unchecked") // safe because of ::isInstance check
425   * ImmutableList<NewType> result =
426   *     (ImmutableList) stream.filter(NewType.class::isInstance).collect(toImmutableList());}
427   * </pre>
428   */
429  @GwtIncompatible // Class.isInstance
430  public final <T> FluentIterable<T> filter(Class<T> type) {
431    return from(Iterables.filter(getDelegate(), type));
432  }
433
434  /**
435   * Returns {@code true} if any element in this fluent iterable satisfies the predicate.
436   *
437   * <p><b>{@code Stream} equivalent:</b> {@link Stream#anyMatch} (same).
438   */
439  public final boolean anyMatch(Predicate<? super E> predicate) {
440    return Iterables.any(getDelegate(), predicate);
441  }
442
443  /**
444   * Returns {@code true} if every element in this fluent iterable satisfies the predicate. If this
445   * fluent iterable is empty, {@code true} is returned.
446   *
447   * <p><b>{@code Stream} equivalent:</b> {@link Stream#allMatch} (same).
448   */
449  public final boolean allMatch(Predicate<? super E> predicate) {
450    return Iterables.all(getDelegate(), predicate);
451  }
452
453  /**
454   * Returns an {@link Optional} containing the first element in this fluent iterable that satisfies
455   * the given predicate, if such an element exists.
456   *
457   * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code null}. If {@code null}
458   * is matched in this fluent iterable, a {@link NullPointerException} will be thrown.
459   *
460   * <p><b>{@code Stream} equivalent:</b> {@code stream.filter(predicate).findFirst()}.
461   */
462  public final Optional<E> firstMatch(Predicate<? super E> predicate) {
463    return Iterables.tryFind(getDelegate(), predicate);
464  }
465
466  /**
467   * Returns a fluent iterable that applies {@code function} to each element of this fluent
468   * iterable.
469   *
470   * <p>The returned fluent iterable's iterator supports {@code remove()} if this iterable's
471   * iterator does. After a successful {@code remove()} call, this fluent iterable no longer
472   * contains the corresponding element.
473   *
474   * <p><b>{@code Stream} equivalent:</b> {@link Stream#map}.
475   */
476  public final <T> FluentIterable<T> transform(Function<? super E, T> function) {
477    return from(Iterables.transform(getDelegate(), function));
478  }
479
480  /**
481   * Applies {@code function} to each element of this fluent iterable and returns a fluent iterable
482   * with the concatenated combination of results. {@code function} returns an Iterable of results.
483   *
484   * <p>The returned fluent iterable's iterator supports {@code remove()} if this function-returned
485   * iterables' iterator does. After a successful {@code remove()} call, the returned fluent
486   * iterable no longer contains the corresponding element.
487   *
488   * <p><b>{@code Stream} equivalent:</b> {@link Stream#flatMap} (using a function that produces
489   * streams, not iterables).
490   *
491   * @since 13.0 (required {@code Function<E, Iterable<T>>} until 14.0)
492   */
493  public <T> FluentIterable<T> transformAndConcat(
494      Function<? super E, ? extends Iterable<? extends T>> function) {
495    return from(FluentIterable.concat(transform(function)));
496  }
497
498  /**
499   * Returns an {@link Optional} containing the first element in this fluent iterable. If the
500   * iterable is empty, {@code Optional.absent()} is returned.
501   *
502   * <p><b>{@code Stream} equivalent:</b> if the goal is to obtain any element, {@link
503   * Stream#findAny}; if it must specifically be the <i>first</i> element, {@code Stream#findFirst}.
504   *
505   * @throws NullPointerException if the first element is null; if this is a possibility, use {@code
506   *     iterator().next()} or {@link Iterables#getFirst} instead.
507   */
508  public final Optional<E> first() {
509    Iterator<E> iterator = getDelegate().iterator();
510    return iterator.hasNext() ? Optional.of(iterator.next()) : Optional.<E>absent();
511  }
512
513  /**
514   * Returns an {@link Optional} containing the last element in this fluent iterable. If the
515   * iterable is empty, {@code Optional.absent()} is returned. If the underlying {@code iterable}
516   * is a {@link List} with {@link java.util.RandomAccess} support, then this operation is
517   * guaranteed to be {@code O(1)}.
518   *
519   * <p><b>{@code Stream} equivalent:</b> {@code stream.reduce((a, b) -> b)}.
520   *
521   * @throws NullPointerException if the last element is null; if this is a possibility, use
522   *     {@link Iterables#getLast} instead.
523   */
524  public final Optional<E> last() {
525    // Iterables#getLast was inlined here so we don't have to throw/catch a NSEE
526
527    // TODO(kevinb): Support a concurrently modified collection?
528    Iterable<E> iterable = getDelegate();
529    if (iterable instanceof List) {
530      List<E> list = (List<E>) iterable;
531      if (list.isEmpty()) {
532        return Optional.absent();
533      }
534      return Optional.of(list.get(list.size() - 1));
535    }
536    Iterator<E> iterator = iterable.iterator();
537    if (!iterator.hasNext()) {
538      return Optional.absent();
539    }
540
541    /*
542     * TODO(kevinb): consider whether this "optimization" is worthwhile. Users with SortedSets tend
543     * to know they are SortedSets and probably would not call this method.
544     */
545    if (iterable instanceof SortedSet) {
546      SortedSet<E> sortedSet = (SortedSet<E>) iterable;
547      return Optional.of(sortedSet.last());
548    }
549
550    while (true) {
551      E current = iterator.next();
552      if (!iterator.hasNext()) {
553        return Optional.of(current);
554      }
555    }
556  }
557
558  /**
559   * Returns a view of this fluent iterable that skips its first {@code numberToSkip} elements. If
560   * this fluent iterable contains fewer than {@code numberToSkip} elements, the returned fluent
561   * iterable skips all of its elements.
562   *
563   * <p>Modifications to this fluent iterable before a call to {@code iterator()} are reflected in
564   * the returned fluent iterable. That is, the its iterator skips the first {@code numberToSkip}
565   * elements that exist when the iterator is created, not when {@code skip()} is called.
566   *
567   * <p>The returned fluent iterable's iterator supports {@code remove()} if the {@code Iterator} of
568   * this fluent iterable supports it. Note that it is <i>not</i> possible to delete the last
569   * skipped element by immediately calling {@code remove()} on the returned fluent iterable's
570   * iterator, as the {@code Iterator} contract states that a call to {@code * remove()} before a
571   * call to {@code next()} will throw an {@link IllegalStateException}.
572   *
573   * <p><b>{@code Stream} equivalent:</b> {@link Stream#skip} (same).
574   */
575  public final FluentIterable<E> skip(int numberToSkip) {
576    return from(Iterables.skip(getDelegate(), numberToSkip));
577  }
578
579  /**
580   * Creates a fluent iterable with the first {@code size} elements of this fluent iterable. If this
581   * fluent iterable does not contain that many elements, the returned fluent iterable will have the
582   * same behavior as this fluent iterable. The returned fluent iterable's iterator supports {@code
583   * remove()} if this fluent iterable's iterator does.
584   *
585   * <p><b>{@code Stream} equivalent:</b> {@link Stream#limit} (same).
586   *
587   * @param maxSize the maximum number of elements in the returned fluent iterable
588   * @throws IllegalArgumentException if {@code size} is negative
589   */
590  public final FluentIterable<E> limit(int maxSize) {
591    return from(Iterables.limit(getDelegate(), maxSize));
592  }
593
594  /**
595   * Determines whether this fluent iterable is empty.
596   *
597   * <p><b>{@code Stream} equivalent:</b> {@code !stream.findAny().isPresent()}.
598   */
599  public final boolean isEmpty() {
600    return !getDelegate().iterator().hasNext();
601  }
602
603  /**
604   * Returns an {@code ImmutableList} containing all of the elements from this fluent iterable in
605   * proper sequence.
606   *
607   * <p><b>{@code Stream} equivalent:</b> {@code ImmutableList.copyOf(stream.iterator())}, or after
608   * the next release of Guava, pass {@link ImmutableList#toImmutableList} to {@code
609   * stream.collect()}.
610   *
611   * @since 14.0 (since 12.0 as {@code toImmutableList()}).
612   */
613  public final ImmutableList<E> toList() {
614    return ImmutableList.copyOf(getDelegate());
615  }
616
617  /**
618   * Returns an {@code ImmutableList} containing all of the elements from this {@code
619   * FluentIterable} in the order specified by {@code comparator}. To produce an {@code
620   * ImmutableList} sorted by its natural ordering, use {@code toSortedList(Ordering.natural())}.
621   *
622   * <p><b>{@code Stream} equivalent:</b> {@code
623   * ImmutableList.copyOf(stream.sorted(comparator).iterator())}, or after the next release of
624   * Guava, pass {@link ImmutableList#toImmutableList} to {@code
625   * stream.sorted(comparator).collect()}.
626   *
627   * @param comparator the function by which to sort list elements
628   * @throws NullPointerException if any element is null
629   * @since 14.0 (since 13.0 as {@code toSortedImmutableList()}).
630   */
631  public final ImmutableList<E> toSortedList(Comparator<? super E> comparator) {
632    return Ordering.from(comparator).immutableSortedCopy(getDelegate());
633  }
634
635  /**
636   * Returns an {@code ImmutableSet} containing all of the elements from this fluent iterable with
637   * duplicates removed.
638   *
639   * <p><b>{@code Stream} equivalent:</b> {@code ImmutableSet.copyOf(stream.iterator())}, or after
640   * the next release of Guava, pass {@link ImmutableSet#toImmutableSet} to {@code
641   * stream.collect()}.
642   *
643   * @since 14.0 (since 12.0 as {@code toImmutableSet()}).
644   */
645  public final ImmutableSet<E> toSet() {
646    return ImmutableSet.copyOf(getDelegate());
647  }
648
649  /**
650   * Returns an {@code ImmutableSortedSet} containing all of the elements from this {@code
651   * FluentIterable} in the order specified by {@code comparator}, with duplicates (determined by
652   * {@code comparator.compare(x, y) == 0}) removed. To produce an {@code ImmutableSortedSet} sorted
653   * by its natural ordering, use {@code toSortedSet(Ordering.natural())}.
654   *
655   * <p><b>{@code Stream} equivalent:</b> {@code ImmutableSortedSet.copyOf(comparator,
656   * stream.iterator())}, or after the next release of Guava, pass {@link
657   * ImmutableSortedSet#toImmutableSortedSet} to {@code stream.collect()}.
658   *
659   * @param comparator the function by which to sort set elements
660   * @throws NullPointerException if any element is null
661   * @since 14.0 (since 12.0 as {@code toImmutableSortedSet()}).
662   */
663  public final ImmutableSortedSet<E> toSortedSet(Comparator<? super E> comparator) {
664    return ImmutableSortedSet.copyOf(comparator, getDelegate());
665  }
666
667  /**
668   * Returns an {@code ImmutableMultiset} containing all of the elements from this fluent iterable.
669   *
670   * <p><b>{@code Stream} equivalent:</b> {@code ImmutableMultiset.copyOf(stream.iterator())}, or
671   * after the next release of Guava, pass {@link ImmutableMultiset#toImmutableMultiset} to {@code
672   * stream.collect()}.
673   *
674   * @since 19.0
675   */
676  public final ImmutableMultiset<E> toMultiset() {
677    return ImmutableMultiset.copyOf(getDelegate());
678  }
679
680  /**
681   * Returns an immutable map whose keys are the distinct elements of this {@code FluentIterable}
682   * and whose value for each key was computed by {@code valueFunction}. The map's iteration order
683   * is the order of the first appearance of each key in this iterable.
684   *
685   * <p>When there are multiple instances of a key in this iterable, it is unspecified whether
686   * {@code valueFunction} will be applied to more than one instance of that key and, if it is,
687   * which result will be mapped to that key in the returned map.
688   *
689   * <p><b>{@code Stream} equivalent:</b> after the next release of Guava, use {@code
690   * stream.collect(ImmutableMap.toImmutableMap(k -> k, valueFunction))}. Before then you can use
691   * {@code ImmutableMap.copyOf(stream.collect(Collectors.toMap(k -> k, valueFunction)))}, but be
692   * aware that this may not preserve the order of entries.
693   *
694   * @throws NullPointerException if any element of this iterable is {@code null}, or if {@code
695   *     valueFunction} produces {@code null} for any key
696   * @since 14.0
697   */
698  public final <V> ImmutableMap<E, V> toMap(Function<? super E, V> valueFunction) {
699    return Maps.toMap(getDelegate(), valueFunction);
700  }
701
702  /**
703   * Creates an index {@code ImmutableListMultimap} that contains the results of applying a
704   * specified function to each item in this {@code FluentIterable} of values. Each element of this
705   * iterable will be stored as a value in the resulting multimap, yielding a multimap with the same
706   * size as this iterable. The key used to store that value in the multimap will be the result of
707   * calling the function on that value. The resulting multimap is created as an immutable snapshot.
708   * In the returned multimap, keys appear in the order they are first encountered, and the values
709   * corresponding to each key appear in the same order as they are encountered.
710   *
711   * <p><b>{@code Stream} equivalent:</b> {@code stream.collect(Collectors.groupingBy(keyFunction))}
712   * behaves similarly, but returns a mutable {@code Map<K, List<E>>} instead, and may not preserve
713   * the order of entries).
714   *
715   * @param keyFunction the function used to produce the key for each value
716   * @throws NullPointerException if any of the following cases is true:
717   *     <ul>
718   *     <li>{@code keyFunction} is null
719   *     <li>An element in this fluent iterable is null
720   *     <li>{@code keyFunction} returns {@code null} for any element of this iterable
721   *     </ul>
722   *
723   * @since 14.0
724   */
725  public final <K> ImmutableListMultimap<K, E> index(Function<? super E, K> keyFunction) {
726    return Multimaps.index(getDelegate(), keyFunction);
727  }
728
729  /**
730   * Returns a map with the contents of this {@code FluentIterable} as its {@code values}, indexed
731   * by keys derived from those values. In other words, each input value produces an entry in the
732   * map whose key is the result of applying {@code keyFunction} to that value. These entries appear
733   * in the same order as they appeared in this fluent iterable. Example usage:
734   *
735   * <pre>{@code
736   * Color red = new Color("red", 255, 0, 0);
737   * ...
738   * FluentIterable<Color> allColors = FluentIterable.from(ImmutableSet.of(red, green, blue));
739   *
740   * Map<String, Color> colorForName = allColors.uniqueIndex(toStringFunction());
741   * assertThat(colorForName).containsEntry("red", red);
742   * }</pre>
743   *
744   * <p>If your index may associate multiple values with each key, use {@link #index(Function)
745   * index}.
746   *
747   * <p><b>{@code Stream} equivalent:</b> after the next release of Guava, use {@code
748   * stream.collect(ImmutableMap.toImmutableMap(keyFunction, v -> v))}. Before then you can use
749   * {@code ImmutableMap.copyOf(stream.collect(Collectors.toMap(keyFunction, v -> v)))}, but be
750   * aware that this may not preserve the order of entries.
751   *
752   * @param keyFunction the function used to produce the key for each value
753   * @return a map mapping the result of evaluating the function {@code keyFunction} on each value
754   *     in this fluent iterable to that value
755   * @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one
756   *     value in this fluent iterable
757   * @throws NullPointerException if any elements of this fluent iterable is null, or if {@code
758   *     keyFunction} produces {@code null} for any value
759   * @since 14.0
760   */
761  public final <K> ImmutableMap<K, E> uniqueIndex(Function<? super E, K> keyFunction) {
762    return Maps.uniqueIndex(getDelegate(), keyFunction);
763  }
764
765  /**
766   * Returns an array containing all of the elements from this fluent iterable in iteration order.
767   *
768   * <p><b>{@code Stream} equivalent:</b> if an object array is acceptable, use
769   * {@code stream.toArray()}; if {@code type} is a class literal such as {@code MyType.class}, use
770   * {@code stream.toArray(MyType[]::new)}. Otherwise use {@code stream.toArray(
771   * len -> (E[]) Array.newInstance(type, len))}.
772   *
773   * @param type the type of the elements
774   * @return a newly-allocated array into which all the elements of this fluent iterable have been
775   *     copied
776   */
777  @GwtIncompatible // Array.newArray(Class, int)
778  public final E[] toArray(Class<E> type) {
779    return Iterables.toArray(getDelegate(), type);
780  }
781
782  /**
783   * Copies all the elements from this fluent iterable to {@code collection}. This is equivalent to
784   * calling {@code Iterables.addAll(collection, this)}.
785   *
786   * <p><b>{@code Stream} equivalent:</b> {@code stream.forEachOrdered(collection::add)} or
787   * {@code stream.forEach(collection::add)}.
788   *
789   * @param collection the collection to copy elements to
790   * @return {@code collection}, for convenience
791   * @since 14.0
792   */
793  @CanIgnoreReturnValue
794  public final <C extends Collection<? super E>> C copyInto(C collection) {
795    checkNotNull(collection);
796    Iterable<E> iterable = getDelegate();
797    if (iterable instanceof Collection) {
798      collection.addAll(Collections2.cast(iterable));
799    } else {
800      for (E item : iterable) {
801        collection.add(item);
802      }
803    }
804    return collection;
805  }
806
807  /**
808   * Returns a {@link String} containing all of the elements of this fluent iterable joined with
809   * {@code joiner}.
810   *
811   * <p><b>{@code Stream} equivalent:</b> {@code joiner.join(stream.iterator())}, or, if you are not
812   * using any optional {@code Joiner} features,
813   * {@code stream.collect(Collectors.joining(delimiter)}.
814   *
815   * @since 18.0
816   */
817  @Beta
818  public final String join(Joiner joiner) {
819    return joiner.join(this);
820  }
821
822  /**
823   * Returns the element at the specified position in this fluent iterable.
824   *
825   * <p><b>{@code Stream} equivalent:</b> {@code stream.skip(position).findFirst().get()} (but note
826   * that this throws different exception types, and throws an exception if {@code null} would be
827   * returned).
828   *
829   * @param position position of the element to return
830   * @return the element at the specified position in this fluent iterable
831   * @throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to
832   *     the size of this fluent iterable
833   */
834  // TODO(kevinb): add @Nullable?
835  public final E get(int position) {
836    return Iterables.get(getDelegate(), position);
837  }
838
839  /**
840   * Function that transforms {@code Iterable<E>} into a fluent iterable.
841   */
842  private static class FromIterableFunction<E> implements Function<Iterable<E>, FluentIterable<E>> {
843    @Override
844    public FluentIterable<E> apply(Iterable<E> fromObject) {
845      return FluentIterable.from(fromObject);
846    }
847  }
848}