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