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