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