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 java.util.stream.Stream#of(Object[])
154   * Stream.of(T...)}.
155   *
156   * @since 20.0 (since 18.0 as an overload of {@code of})
157   */
158  @Beta
159  public static <E> FluentIterable<E> from(E[] elements) {
160    return from(Arrays.asList(elements));
161  }
162
163  /**
164   * Construct a fluent iterable from another fluent iterable. This is obviously never necessary,
165   * but is intended to help call out cases where one migration from {@code Iterable} to
166   * {@code FluentIterable} has obviated the need to explicitly convert to a {@code FluentIterable}.
167   *
168   * @deprecated instances of {@code FluentIterable} don't need to be converted to
169   *     {@code FluentIterable}
170   */
171  @Deprecated
172  public static <E> FluentIterable<E> from(FluentIterable<E> iterable) {
173    return checkNotNull(iterable);
174  }
175
176  /**
177   * Returns a fluent iterable that combines two iterables. The returned iterable has an iterator
178   * that traverses the elements in {@code a}, followed by the elements in {@code b}. The source
179   * iterators are not polled until necessary.
180   *
181   * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input
182   * iterator supports it.
183   *
184   * <p><b>{@code Stream} equivalent:</b> {@link Stream#concat}.
185   *
186   * @since 20.0
187   */
188  @Beta
189  public static <T> FluentIterable<T> concat(Iterable<? extends T> a, Iterable<? extends T> b) {
190    return concat(ImmutableList.of(a, b));
191  }
192
193  /**
194   * Returns a fluent iterable that combines three iterables. The returned iterable has an iterator
195   * that traverses the elements in {@code a}, followed by the elements in {@code b}, followed by
196   * the elements in {@code c}. The source iterators are not polled until necessary.
197   *
198   * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input
199   * iterator supports it.
200   *
201   * <p><b>{@code Stream} equivalent:</b> use nested calls to {@link Stream#concat}, or see the
202   * advice in {@link #concat(Iterable...)}.
203   *
204   * @since 20.0
205   */
206  @Beta
207  public static <T> FluentIterable<T> concat(
208      Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c) {
209    return concat(ImmutableList.of(a, b, c));
210  }
211
212  /**
213   * Returns a fluent iterable that combines four iterables. The returned iterable has an iterator
214   * that traverses the elements in {@code a}, followed by the elements in {@code b}, followed by
215   * the elements in {@code c}, followed by the elements in {@code d}. The source iterators are not
216   * polled until necessary.
217   *
218   * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input
219   * iterator supports it.
220   *
221   * <p><b>{@code Stream} equivalent:</b> use nested calls to {@link Stream#concat}, or see the
222   * advice in {@link #concat(Iterable...)}.
223   *
224   * @since 20.0
225   */
226  @Beta
227  public static <T> FluentIterable<T> concat(
228      Iterable<? extends T> a,
229      Iterable<? extends T> b,
230      Iterable<? extends T> c,
231      Iterable<? extends T> d) {
232    return concat(ImmutableList.of(a, b, c, d));
233  }
234
235  /**
236   * Returns a fluent iterable that combines several iterables. The returned iterable has an
237   * iterator that traverses the elements of each iterable in {@code inputs}. The input iterators
238   * are not polled until necessary.
239   *
240   * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input
241   * iterator supports it.
242   *
243   * <p><b>{@code Stream} equivalent:</b> to concatenate an arbitrary number of streams, use {@code
244   * Stream.of(stream1, stream2, ...).flatMap(s -> s)}. If the sources are iterables, use {@code
245   * Stream.of(iter1, iter2, ...).flatMap(Streams::stream)}.
246   *
247   * @throws NullPointerException if any of the provided iterables is {@code null}
248   * @since 20.0
249   */
250  @Beta
251  public static <T> FluentIterable<T> concat(Iterable<? extends T>... inputs) {
252    return concat(ImmutableList.copyOf(inputs));
253  }
254
255  /**
256   * Returns a fluent iterable that combines several iterables. The returned iterable has an
257   * iterator that traverses the elements of each iterable in {@code inputs}. The input iterators
258   * are not polled until necessary.
259   *
260   * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input
261   * iterator supports it. The methods of the returned iterable may throw {@code
262   * NullPointerException} if any of the input iterators is {@code null}.
263   *
264   * <p><b>{@code Stream} equivalent:</b> {@code streamOfStreams.flatMap(s -> s)} or {@code
265   * streamOfIterables.flatMap(Streams::stream)}. (See {@link Streams#stream}.)
266   *
267   * @since 20.0
268   */
269  @Beta
270  public static <T> FluentIterable<T> concat(
271      final Iterable<? extends Iterable<? extends T>> inputs) {
272    checkNotNull(inputs);
273    return new FluentIterable<T>() {
274      @Override
275      public Iterator<T> iterator() {
276        return Iterators.concat(Iterables.transform(inputs, Iterables.<T>toIterator()).iterator());
277      }
278    };
279  }
280
281  /**
282   * Returns a fluent iterable containing no elements.
283   *
284   * <p><b>{@code Stream} equivalent:</b> {@link Stream#empty}.
285   *
286   * @since 20.0
287   */
288  @Beta
289  public static <E> FluentIterable<E> of() {
290    return FluentIterable.from(ImmutableList.<E>of());
291  }
292
293  /**
294   * Returns a fluent iterable containing {@code elements} in the specified order.
295   *
296   * <p>The returned iterable is modifiable, but modifications do not affect the input array.
297   *
298   * <p><b>{@code Stream} equivalent:</b> {@link java.util.stream.Stream#of(Object[])
299   * Stream.of(T...)}.
300   *
301   * @deprecated Use {@link #from(Object[])} instead (but note the differences in mutability). This
302   *     method will be removed in Guava release 21.0.
303   * @since 18.0
304   */
305  @Beta
306  @Deprecated
307  public static <E> FluentIterable<E> of(E[] elements) {
308    return from(Lists.newArrayList(elements));
309  }
310
311  /**
312   * Returns a fluent iterable containing the specified elements in order.
313   *
314   * <p><b>{@code Stream} equivalent:</b> {@link java.util.stream.Stream#of(Object[])
315   * 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> {@link 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   * e}, use {@code Stream.generate(() -> e)}. Otherwise, collect your stream into a collection and
370   * use {@code Stream.generate(() -> collection).flatMap(Collection::stream)}.
371   */
372  public final FluentIterable<E> cycle() {
373    return from(Iterables.cycle(getDelegate()));
374  }
375
376  /**
377   * Returns a fluent iterable whose iterators traverse first the elements of this fluent iterable,
378   * followed by those of {@code other}. The iterators are not polled until necessary.
379   *
380   * <p>The returned iterable's {@code Iterator} supports {@code remove()} when the corresponding
381   * {@code Iterator} supports it.
382   *
383   * <p><b>{@code Stream} equivalent:</b> {@link Stream#concat}.
384   *
385   * @since 18.0
386   */
387  @Beta
388  public final FluentIterable<E> append(Iterable<? extends E> other) {
389    return from(FluentIterable.concat(getDelegate(), other));
390  }
391
392  /**
393   * Returns a fluent iterable whose iterators traverse first the elements of this fluent iterable,
394   * followed by {@code elements}.
395   *
396   * <p><b>{@code Stream} equivalent:</b> {@code Stream.concat(thisStream, Stream.of(elements))}.
397   *
398   * @since 18.0
399   */
400  @Beta
401  public final FluentIterable<E> append(E... elements) {
402    return from(FluentIterable.concat(getDelegate(), Arrays.asList(elements)));
403  }
404
405  /**
406   * Returns the elements from this fluent iterable that satisfy a predicate. The resulting fluent
407   * iterable's iterator does not support {@code remove()}.
408   *
409   * <p><b>{@code Stream} equivalent:</b> {@link Stream#filter} (same).
410   */
411  public final FluentIterable<E> filter(Predicate<? super E> predicate) {
412    return from(Iterables.filter(getDelegate(), predicate));
413  }
414
415  /**
416   * Returns the elements from this fluent iterable that are instances of class {@code type}.
417   *
418   * <p><b>{@code Stream} equivalent:</b> {@code stream.filter(type::isInstance).map(type::cast)}.
419   * This does perform a little more work than necessary, so another option is to insert an
420   * unchecked cast at some later point:
421   *
422   * <pre>
423   * {@code @SuppressWarnings("unchecked") // safe because of ::isInstance check
424   * ImmutableList<NewType> result =
425   *     (ImmutableList) stream.filter(NewType.class::isInstance).collect(toImmutableList());}
426   * </pre>
427   */
428  @GwtIncompatible // Class.isInstance
429  public final <T> FluentIterable<T> filter(Class<T> type) {
430    return from(Iterables.filter(getDelegate(), type));
431  }
432
433  /**
434   * Returns {@code true} if any element in this fluent iterable satisfies the predicate.
435   *
436   * <p><b>{@code Stream} equivalent:</b> {@link Stream#anyMatch} (same).
437   */
438  public final boolean anyMatch(Predicate<? super E> predicate) {
439    return Iterables.any(getDelegate(), predicate);
440  }
441
442  /**
443   * Returns {@code true} if every element in this fluent iterable satisfies the predicate. If this
444   * fluent iterable is empty, {@code true} is returned.
445   *
446   * <p><b>{@code Stream} equivalent:</b> {@link Stream#allMatch} (same).
447   */
448  public final boolean allMatch(Predicate<? super E> predicate) {
449    return Iterables.all(getDelegate(), predicate);
450  }
451
452  /**
453   * Returns an {@link Optional} containing the first element in this fluent iterable that satisfies
454   * the given predicate, if such an element exists.
455   *
456   * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code null}. If {@code null}
457   * is matched in this fluent iterable, a {@link NullPointerException} will be thrown.
458   *
459   * <p><b>{@code Stream} equivalent:</b> {@code stream.filter(predicate).findFirst()}.
460   */
461  public final Optional<E> firstMatch(Predicate<? super E> predicate) {
462    return Iterables.tryFind(getDelegate(), predicate);
463  }
464
465  /**
466   * Returns a fluent iterable that applies {@code function} to each element of this fluent
467   * iterable.
468   *
469   * <p>The returned fluent iterable's iterator supports {@code remove()} if this iterable's
470   * iterator does. After a successful {@code remove()} call, this fluent iterable no longer
471   * contains the corresponding element.
472   *
473   * <p><b>{@code Stream} equivalent:</b> {@link Stream#map}.
474   */
475  public final <T> FluentIterable<T> transform(Function<? super E, T> function) {
476    return from(Iterables.transform(getDelegate(), function));
477  }
478
479  /**
480   * Applies {@code function} to each element of this fluent iterable and returns a fluent iterable
481   * with the concatenated combination of results. {@code function} returns an Iterable of results.
482   *
483   * <p>The returned fluent iterable's iterator supports {@code remove()} if this function-returned
484   * iterables' iterator does. After a successful {@code remove()} call, the returned fluent
485   * iterable no longer contains the corresponding element.
486   *
487   * <p><b>{@code Stream} equivalent:</b> {@link Stream#flatMap} (using a function that produces
488   * streams, not iterables).
489   *
490   * @since 13.0 (required {@code Function<E, Iterable<T>>} until 14.0)
491   */
492  public <T> FluentIterable<T> transformAndConcat(
493      Function<? super E, ? extends Iterable<? extends T>> function) {
494    return from(FluentIterable.concat(transform(function)));
495  }
496
497  /**
498   * Returns an {@link Optional} containing the first element in this fluent iterable. If the
499   * iterable is empty, {@code Optional.absent()} is returned.
500   *
501   * <p><b>{@code Stream} equivalent:</b> if the goal is to obtain any element, {@link
502   * Stream#findAny}; if it must specifically be the <i>first</i> element, {@code Stream#findFirst}.
503   *
504   * @throws NullPointerException if the first element is null; if this is a possibility, use {@code
505   *     iterator().next()} or {@link Iterables#getFirst} instead.
506   */
507  public final Optional<E> first() {
508    Iterator<E> iterator = getDelegate().iterator();
509    return iterator.hasNext() ? Optional.of(iterator.next()) : Optional.<E>absent();
510  }
511
512  /**
513   * Returns an {@link Optional} containing the last element in this fluent iterable. If the
514   * iterable is empty, {@code Optional.absent()} is returned. If the underlying {@code iterable}
515   * is a {@link List} with {@link java.util.RandomAccess} support, then this operation is
516   * guaranteed to be {@code O(1)}.
517   *
518   * <p><b>{@code Stream} equivalent:</b> {@code stream.reduce((a, b) -> b)}.
519   *
520   * @throws NullPointerException if the last element is null; if this is a possibility, use
521   *     {@link Iterables#getLast} instead.
522   */
523  public final Optional<E> last() {
524    // Iterables#getLast was inlined here so we don't have to throw/catch a NSEE
525
526    // TODO(kevinb): Support a concurrently modified collection?
527    Iterable<E> iterable = getDelegate();
528    if (iterable instanceof List) {
529      List<E> list = (List<E>) iterable;
530      if (list.isEmpty()) {
531        return Optional.absent();
532      }
533      return Optional.of(list.get(list.size() - 1));
534    }
535    Iterator<E> iterator = iterable.iterator();
536    if (!iterator.hasNext()) {
537      return Optional.absent();
538    }
539
540    /*
541     * TODO(kevinb): consider whether this "optimization" is worthwhile. Users with SortedSets tend
542     * to know they are SortedSets and probably would not call this method.
543     */
544    if (iterable instanceof SortedSet) {
545      SortedSet<E> sortedSet = (SortedSet<E>) iterable;
546      return Optional.of(sortedSet.last());
547    }
548
549    while (true) {
550      E current = iterator.next();
551      if (!iterator.hasNext()) {
552        return Optional.of(current);
553      }
554    }
555  }
556
557  /**
558   * Returns a view of this fluent iterable that skips its first {@code numberToSkip} elements. If
559   * this fluent iterable contains fewer than {@code numberToSkip} elements, the returned fluent
560   * iterable skips all of its elements.
561   *
562   * <p>Modifications to this fluent iterable before a call to {@code iterator()} are reflected in
563   * the returned fluent iterable. That is, the its iterator skips the first {@code numberToSkip}
564   * elements that exist when the iterator is created, not when {@code skip()} is called.
565   *
566   * <p>The returned fluent iterable's iterator supports {@code remove()} if the {@code Iterator} of
567   * this fluent iterable supports it. Note that it is <i>not</i> possible to delete the last
568   * skipped element by immediately calling {@code remove()} on the returned fluent iterable's
569   * iterator, as the {@code Iterator} contract states that a call to {@code * remove()} before a
570   * call to {@code next()} will throw an {@link IllegalStateException}.
571   *
572   * <p><b>{@code Stream} equivalent:</b> {@link Stream#skip} (same).
573   */
574  public final FluentIterable<E> skip(int numberToSkip) {
575    return from(Iterables.skip(getDelegate(), numberToSkip));
576  }
577
578  /**
579   * Creates a fluent iterable with the first {@code size} elements of this fluent iterable. If this
580   * fluent iterable does not contain that many elements, the returned fluent iterable will have the
581   * same behavior as this fluent iterable. The returned fluent iterable's iterator supports {@code
582   * remove()} if this fluent iterable's iterator does.
583   *
584   * <p><b>{@code Stream} equivalent:</b> {@link Stream#limit} (same).
585   *
586   * @param maxSize the maximum number of elements in the returned fluent iterable
587   * @throws IllegalArgumentException if {@code size} is negative
588   */
589  public final FluentIterable<E> limit(int maxSize) {
590    return from(Iterables.limit(getDelegate(), maxSize));
591  }
592
593  /**
594   * Determines whether this fluent iterable is empty.
595   *
596   * <p><b>{@code Stream} equivalent:</b> {@code !stream.findAny().isPresent()}.
597   */
598  public final boolean isEmpty() {
599    return !getDelegate().iterator().hasNext();
600  }
601
602  /**
603   * Returns an {@code ImmutableList} containing all of the elements from this fluent iterable in
604   * proper sequence.
605   *
606   * <p><b>{@code Stream} equivalent:</b> pass {@link ImmutableList#toImmutableList} to {@code
607   * stream.collect()}.
608   *
609   * @throws NullPointerException if any element is {@code null}
610   * @since 14.0 (since 12.0 as {@code toImmutableList()}).
611   */
612  public final ImmutableList<E> toList() {
613    return ImmutableList.copyOf(getDelegate());
614  }
615
616  /**
617   * Returns an {@code ImmutableList} containing all of the elements from this {@code
618   * FluentIterable} in the order specified by {@code comparator}. To produce an {@code
619   * ImmutableList} sorted by its natural ordering, use {@code toSortedList(Ordering.natural())}.
620   *
621   * <p><b>{@code Stream} equivalent:</b> pass {@link ImmutableList#toImmutableList} to {@code
622   * stream.sorted(comparator).collect()}.
623   *
624   * @param comparator the function by which to sort list elements
625   * @throws NullPointerException if any element of this iterable is {@code null}
626   * @since 14.0 (since 13.0 as {@code toSortedImmutableList()}).
627   */
628  public final ImmutableList<E> toSortedList(Comparator<? super E> comparator) {
629    return Ordering.from(comparator).immutableSortedCopy(getDelegate());
630  }
631
632  /**
633   * Returns an {@code ImmutableSet} containing all of the elements from this fluent iterable with
634   * duplicates removed.
635   *
636   * <p><b>{@code Stream} equivalent:</b> pass {@link ImmutableSet#toImmutableSet} to {@code
637   * stream.collect()}.
638   *
639   * @throws NullPointerException if any element is {@code null}
640   * @since 14.0 (since 12.0 as {@code toImmutableSet()}).
641   */
642  public final ImmutableSet<E> toSet() {
643    return ImmutableSet.copyOf(getDelegate());
644  }
645
646  /**
647   * Returns an {@code ImmutableSortedSet} containing all of the elements from this {@code
648   * FluentIterable} in the order specified by {@code comparator}, with duplicates (determined by
649   * {@code comparator.compare(x, y) == 0}) removed. To produce an {@code ImmutableSortedSet} sorted
650   * by its natural ordering, use {@code toSortedSet(Ordering.natural())}.
651   *
652   * <p><b>{@code Stream} equivalent:</b> pass {@link
653   * ImmutableSortedSet#toImmutableSortedSet} to {@code stream.collect()}.
654   *
655   * @param comparator the function by which to sort set elements
656   * @throws NullPointerException if any element of this iterable is {@code null}
657   * @since 14.0 (since 12.0 as {@code toImmutableSortedSet()}).
658   */
659  public final ImmutableSortedSet<E> toSortedSet(Comparator<? super E> comparator) {
660    return ImmutableSortedSet.copyOf(comparator, getDelegate());
661  }
662
663  /**
664   * Returns an {@code ImmutableMultiset} containing all of the elements from this fluent iterable.
665   *
666   * <p><b>{@code Stream} equivalent:</b> pass {@link ImmutableMultiset#toImmutableMultiset} to
667   * {@code
668   * stream.collect()}.
669   *
670   * @throws NullPointerException if any element is null
671   * @since 19.0
672   */
673  public final ImmutableMultiset<E> toMultiset() {
674    return ImmutableMultiset.copyOf(getDelegate());
675  }
676
677  /**
678   * Returns an immutable map whose keys are the distinct elements of this {@code FluentIterable}
679   * and whose value for each key was computed by {@code valueFunction}. The map's iteration order
680   * is the order of the first appearance of each key in this iterable.
681   *
682   * <p>When there are multiple instances of a key in this iterable, it is unspecified whether
683   * {@code valueFunction} will be applied to more than one instance of that key and, if it is,
684   * which result will be mapped to that key in the returned map.
685   *
686   * <p><b>{@code Stream} equivalent:</b> {@code
687   * stream.collect(ImmutableMap.toImmutableMap(k -> k, valueFunction))}.
688   *
689   * @throws NullPointerException if any element of this iterable is {@code null}, or if {@code
690   *     valueFunction} produces {@code null} for any key
691   * @since 14.0
692   */
693  public final <V> ImmutableMap<E, V> toMap(Function<? super E, V> valueFunction) {
694    return Maps.toMap(getDelegate(), valueFunction);
695  }
696
697  /**
698   * Creates an index {@code ImmutableListMultimap} that contains the results of applying a
699   * specified function to each item in this {@code FluentIterable} of values. Each element of this
700   * iterable will be stored as a value in the resulting multimap, yielding a multimap with the same
701   * size as this iterable. The key used to store that value in the multimap will be the result of
702   * calling the function on that value. The resulting multimap is created as an immutable snapshot.
703   * In the returned multimap, keys appear in the order they are first encountered, and the values
704   * corresponding to each key appear in the same order as they are encountered.
705   *
706   * <p><b>{@code Stream} equivalent:</b> {@code stream.collect(Collectors.groupingBy(keyFunction))}
707   * behaves similarly, but returns a mutable {@code Map<K, List<E>>} instead, and may not preserve
708   * the order of entries).
709   *
710   * @param keyFunction the function used to produce the key for each value
711   * @throws NullPointerException if any element of this iterable is {@code null}, or if {@code
712   *     keyFunction} produces {@code null} for any key
713   * @since 14.0
714   */
715  public final <K> ImmutableListMultimap<K, E> index(Function<? super E, K> keyFunction) {
716    return Multimaps.index(getDelegate(), keyFunction);
717  }
718
719  /**
720   * Returns a map with the contents of this {@code FluentIterable} as its {@code values}, indexed
721   * by keys derived from those values. In other words, each input value produces an entry in the
722   * map whose key is the result of applying {@code keyFunction} to that value. These entries appear
723   * in the same order as they appeared in this fluent iterable. Example usage:
724   *
725   * <pre>{@code
726   * Color red = new Color("red", 255, 0, 0);
727   * ...
728   * FluentIterable<Color> allColors = FluentIterable.from(ImmutableSet.of(red, green, blue));
729   *
730   * Map<String, Color> colorForName = allColors.uniqueIndex(toStringFunction());
731   * assertThat(colorForName).containsEntry("red", red);
732   * }</pre>
733   *
734   * <p>If your index may associate multiple values with each key, use {@link #index(Function)
735   * index}.
736   *
737   * <p><b>{@code Stream} equivalent:</b> {@code
738   * stream.collect(ImmutableMap.toImmutableMap(keyFunction, v -> v))}.
739   *
740   * @param keyFunction the function used to produce the key for each value
741   * @return a map mapping the result of evaluating the function {@code keyFunction} on each value
742   *     in this fluent iterable to that value
743   * @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one
744   *     value in this fluent iterable
745   * @throws NullPointerException if any element of this iterable is {@code null}, or if {@code
746   *     keyFunction} produces {@code null} for any key
747   * @since 14.0
748   */
749  public final <K> ImmutableMap<K, E> uniqueIndex(Function<? super E, K> keyFunction) {
750    return Maps.uniqueIndex(getDelegate(), keyFunction);
751  }
752
753  /**
754   * Returns an array containing all of the elements from this fluent iterable in iteration order.
755   *
756   * <p><b>{@code Stream} equivalent:</b> if an object array is acceptable, use
757   * {@code stream.toArray()}; if {@code type} is a class literal such as {@code MyType.class}, use
758   * {@code stream.toArray(MyType[]::new)}. Otherwise use {@code stream.toArray(
759   * len -> (E[]) Array.newInstance(type, len))}.
760   *
761   * @param type the type of the elements
762   * @return a newly-allocated array into which all the elements of this fluent iterable have been
763   *     copied
764   */
765  @GwtIncompatible // Array.newArray(Class, int)
766  public final E[] toArray(Class<E> type) {
767    return Iterables.toArray(getDelegate(), type);
768  }
769
770  /**
771   * Copies all the elements from this fluent iterable to {@code collection}. This is equivalent to
772   * calling {@code Iterables.addAll(collection, this)}.
773   *
774   * <p><b>{@code Stream} equivalent:</b> {@code stream.forEachOrdered(collection::add)} or
775   * {@code stream.forEach(collection::add)}.
776   *
777   * @param collection the collection to copy elements to
778   * @return {@code collection}, for convenience
779   * @since 14.0
780   */
781  @CanIgnoreReturnValue
782  public final <C extends Collection<? super E>> C copyInto(C collection) {
783    checkNotNull(collection);
784    Iterable<E> iterable = getDelegate();
785    if (iterable instanceof Collection) {
786      collection.addAll(Collections2.cast(iterable));
787    } else {
788      for (E item : iterable) {
789        collection.add(item);
790      }
791    }
792    return collection;
793  }
794
795  /**
796   * Returns a {@link String} containing all of the elements of this fluent iterable joined with
797   * {@code joiner}.
798   *
799   * <p><b>{@code Stream} equivalent:</b> {@code joiner.join(stream.iterator())}, or, if you are not
800   * using any optional {@code Joiner} features,
801   * {@code stream.collect(Collectors.joining(delimiter)}.
802   *
803   * @since 18.0
804   */
805  @Beta
806  public final String join(Joiner joiner) {
807    return joiner.join(this);
808  }
809
810  /**
811   * Returns the element at the specified position in this fluent iterable.
812   *
813   * <p><b>{@code Stream} equivalent:</b> {@code stream.skip(position).findFirst().get()} (but note
814   * that this throws different exception types, and throws an exception if {@code null} would be
815   * returned).
816   *
817   * @param position position of the element to return
818   * @return the element at the specified position in this fluent iterable
819   * @throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to
820   *     the size of this fluent iterable
821   */
822  // TODO(kevinb): add @Nullable?
823  public final E get(int position) {
824    return Iterables.get(getDelegate(), position);
825  }
826
827  /**
828   * Returns a stream of this fluent iterable's contents (similar to calling {@link
829   * Collection#stream} on a collecion).
830   *
831   * <p><b>Note:</b> the earlier in the chain you can switch to {@code Stream} usage (ideally not
832   * going through {@code FluentIterable} at all), the more performant and idiomatic your code will
833   * be. This method is a transitional aid, to be used only when really necessary.
834   *
835   * @since 21.0
836   */
837  public final Stream<E> stream() {
838    return Streams.stream(getDelegate());
839  }
840
841  /**
842   * Function that transforms {@code Iterable<E>} into a fluent iterable.
843   */
844  private static class FromIterableFunction<E> implements Function<Iterable<E>, FluentIterable<E>> {
845    @Override
846    public FluentIterable<E> apply(Iterable<E> fromObject) {
847      return FluentIterable.from(fromObject);
848    }
849  }
850}